However, if you are new to the concept, here is a basic introduction to REST API.
Representational State Transfer, commonly known as REST APIs, are a standard for build networked applications. REST APIs use the HTTP requests to perform the operations such as reading the data, posting the data, deleting the data, and more. REST APIs are incredibly powerful and provide extensibility from a variety of applications and use cases.
In this tutorial, we will dive into the world of REST APIs by learning how to build a basic REST API using C#.
Project Requirements
Due to the scope of this tutorial, we will cover the fundamentals of building a REST API. We will use the ASP.NET Core which is an incredible framework for building modern web applications.
For you to follow along with this guide, ensure that you have the following:
- Installed Visual Studio
- Installed ASP.NET Core
With the given requirements met, we can proceed.
Project Setup
The first step is to create the web application that serves as the API endpoint. From the visual studio, create a new project and choose the ASP.NET Core Web API as the project base.
Give a name for your project and configure the application options. Our example app has the configuration as follows:
Create a Model
Next, create a basic model with the source code as shown in the following:
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
}
Create a Controller
The next step is defining the controller for the API. This includes the route mapping and format as shown in the following code:
namespace BasicWebApi.Controllers
{
[ApiController]
[Route("[api/controller]")]
public class EmployeeController : ControllerBase
{
private readonly List<Employee> _employees = new List<Employee>
{
new Employee { Id = 1, Name = "Alex Non", Position = "Database Developer" },
new Employee { Id = 2, Name = "Alic Popovic", Position = "DevOps Engineer" }
};
[HttpGet]
public IEnumerable<Employee> GetEmployees()
{
return _employees;
}
[HttpGet("{id}")]
public ActionResult<Employee> GetEmployee(int id)
{
var employee = _employees.FirstOrDefault(e => e.Id == id);
if (employee == null)
{
return NotFound();
}
return employee;
}
}
}
In the given controller, we define two actions: the GetEmployees controller which returns the list of employees and the GetEmployee controller which returns a single employee by ID.
Consume the API
Once we define the API and how it works, we need to create a consumer application which can query and fetch the data from the API. You can follow the similar steps to create a new project and add the source code as follows:
using Newtonsoft.Json;
class Program
{
static async Task Main(string[] args)
{
string baseUrl = "https://localhost:5001/api/employees";
using (HttpClient client = new HttpClient())
{
try
{
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
using (HttpContent content = res.Content)
{
var data = await content.ReadAsStringAsync();
if (data != null)
{
var employees = JsonConvert.DeserializeObject<List<Employee>>(data);
foreach (var emp in employees)
{
Console.WriteLine($"Id: {emp.Id}, Name: {emp.Name}, Position: {emp.Position}");
}
}
else
{
Console.WriteLine("No data retrieved.");
}
}
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}
The previous code uses the HttpClient to send an HTTP get request to the API. We then read the response and deserialize the JSON data using the “Newtonsoft.Json” library. Ensure that this library is installed on your machine before proceeding.
Finally, we can print the data to the console.
Conclusion
This covers the basics of building and setting up a basic REST API using C# and the .NET Core Web API.