Build a simple RESTful API in .NET 5 (ASP.Net Core)

Dominique Kleeven
4 min readFeb 12, 2021

A simple tutorial on how to create a quick RESTful API in .NET 5

Prerequisites

This guide is for those who are quite new to ASP.NET Core development and have some knowledge about RESTful APIs and C# Development. The main goal of this guide is to quickly explain how to create a REST API and return some data.

Getting Started

Create a new project and choose the ASP.NET Core Web API

Create A New ASP.NET Core Web API

This creates a simple project that includes 1 default API Controller (WeatherForecastController.cs)

How your solution should look after creating a new project.

Creating our Classes and Methods

For the next step, we’ll remove the existing WeatherForecast controller and object and create a new domain object/class (User)

  1. Create a User Class.

User.cs

public class User
{
public Guid Guid { get; set; }

public string Email { get; set; }

public string Password { get; set; }

public string Name { get; set; }

public User()
{

}
}

2. Create a UsersController class inside the Controllers folder and define the following methods (no worries I’ll explain how everything works):

UsersController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace SimpleAPI.Controllers
{
[Controller]
[Route("api/[controller]")]
public class UsersController : Controller
{
private readonly List<User> _users = new List<User>();

public UsersController()
{
_users.Add(new User()
{
Email = "john@example.com",
Name = "John Doe",
Password = "password123",
Guid = Guid.NewGuid()
});

_users.Add(new User()
{
Email = "jane@example.com",
Name = "Jane Doe",
Password = "password123",
Guid = Guid.Parse("587671b5-3c0a-46e9-9015-624220c614ca")
});
}

[HttpGet]
public ActionResult<List<User>> Index()
{
return _users; //returns all users.
}

[HttpGet("{guid}")]
public ActionResult<User> GetByGuid(Guid guid)
{
return Ok(_users.FirstOrDefault(u => u.Guid == guid));
}

[HttpPost]
public ActionResult<User> Insert([FromBody] User user)
{
_users.Add(user);
return user;
}

}
}
Explanation:[Controller]
[Route("api/[controller]")]
public class UsersController : Controller

The above code tells ASP.NET Core that this is a controller and lists on the /api/[controllername] endpoint. (In this case: /api/users)

The endpoints themselves are added by using the [HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete] annotations.

[HttpGet]
public ActionResult<List<User>> Index()
{
return _users; //returns all users.
}

Returns all users, ASP.NET Core will automatically change your C# object to JSON.

[HttpGet("{guid}")]
public ActionResult<User> GetByGuid(Guid guid)
{
return Ok(_users.FirstOrDefault(u => u.Guid == guid));
}

Returns a specified user by its Guid. The [HttpGet(“{guid}] annotation tells the endpoint which parameter it needs.

[HttpPost]
public ActionResult<User> Insert([FromBody] User user)
{
_users.Add(user);
return user;
}

Accepts a user and adds it to the in-memory user list.

That’s all there is to it.

3. Start the application (It should open a browser window if not goto: https://localhost:5001/swagger/index.html)

Don’t see a swagger page?

In Startup.cs make sure your ConfigureServices method has

services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "SimpleAPI", Version = "v1"}); });

And Configure has

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SimpleAPI v1"));
}

Fetching data from the API using Swagger

In .NET 5 the standard Web API will automatically add a swagger documentation page. This allows you to easily test/use your Rest API while developing it.

Click on Try it out and Execute. It should return all users in the JSON format.

[
{
"guid": "fa4b96fc-f4aa-44fc-a5ed-b3f7dbf80bf1",
"email": "john@example.com",
"password": "password123",
"name": "John Doe"
},
{
"guid": "587671b5-3c0a-46e9-9015-624220c614ca",
"email": "jane@example.com",
"password": "password123",
"name": "Jane Doe"
}
]

This basically creates a GET call to https://localhost:5001/api/users If you go there yourself you’ll also get a JSON response with all existing users.

Feel free to try the other Swagger actions/methods.

Want to read more about this topic? Check out my full tutorial on creating a CRUD RESTFul API in .NET 5 using MongoDB

Thanks for reading, hope you’ve learned something.

--

--