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

Prerequisites

Getting Started

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

Create A New ASP.NET Core Web API
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)

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()
{

}
}
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
[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;
}
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "SimpleAPI", Version = "v1"}); });
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.

[
{
"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"
}
]

Short Coding Tutorials for .NET & NodeJS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store