Jump to content

How to Create and Consume REST APIs in C#


Linux Hint

Recommended Posts

REST APIs need no introduction to developers. They are exceptional applications that provide communication interfaces for networked applications. When you are learning a new language, one of the best projects to work on is attempting to build a REST API application.

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:

  1. Installed Visual Studio
  2. 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.

word-image-402389-1.png

Give a name for your project and configure the application options. Our example app has the configuration as follows:

word-image-402389-2.png

Create a Model

Next, create a basic model with the source code as shown in the following:

public class Employee
{
    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:

using Microsoft.AspNetCore.Mvc;
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 BasicWebApi;
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.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...