Rest API in C#

Adrián Bailador - Mar 5 - - Dev Community

Due to changing times, companies, thankfully, no longer create a monolithic application that does everything. Instead, that same application is divided into different modules or small projects, each performing a specific function.

We call the use of small projects to build a larger application the microservices architecture. The reason I mention this architecture here is that microservices rely on or are based on APIs.

  1. What is an API?

There are various ways to define what an API is. Personally, I define an API as the entry point from the outside into your project.

Of course, the same applies when we are the ones consuming different APIs.

We have our front end, which consumes the back end through an API, and in turn, the back end consumes two other services through APIs.

An API can return either a single character or a list with thousands of elements.

  1. Types of API in C#

In C#, we have two options for creating APIs: SOAP and REST.

Both options have different characteristics, but the ultimate goal is the same: sending information between a client and a server.

2.1 Differences between SOAP and REST

  • Protocol: A significant difference is that SOAP is a protocol, while REST is an architecture that operates on the HTTP protocol.

  • Development: Developing a SOAP service takes more time, both for the client and the server. In REST, we operate over the HTTP protocol, which means that to receive/send information, we do it through web requests, through the URL, or using the message body. Developing a REST API is much faster than a SOAP web service.

SOAP has advantages in other aspects, for example, it can maintain state between several requests, while in REST, each request is individual. Due to the mentioned file (.wsdl) with XML and DTD, SOAP services are much more secure.

  1. Creating an API in C#

When creating APIs, we should design the endpoints with CRUD in mind.

3.1 What is CRUD?

CRUD is an acronym referring to its initials:

  • Create (create): Using the HTTP POST method.
  • Read (read): Using the HTTP GET method.
  • Update (update): Using HTTP PUT.
  • Delete (delete): Using HTTP DELETE.

There are more HTTP methods, but 99.9% of actions are performed with these.

In C#, our entry point will be the controllers.

To do this, we must ensure that within the Startup.cs class, we have the service that adds the controllers.

   public void ConfigureServices(IServiceCollection services) 
   { 
       services.AddControllers(); 
   }
Enter fullscreen mode Exit fullscreen mode

And in this same class, in the Configure method, within UseEndpoints, we must indicate to look for these endpoints in the controllers with the condition endpoints.MapControllers().

   app.UseEndpoints(endpoints => 
   { 
       endpoints.MapGet("/", async context => 
       { 
           await context.Response.WriteAsync("Hello World!"); 
       }); 
       endpoints.MapControllers(); 
   });
Enter fullscreen mode Exit fullscreen mode

3.2 Creating endpoints

In C#, when creating endpoints for an API, we do it in a controller. Therefore, we create a controller class ExampleController and add the attribute [ApiController], and we must import the library using Microsoft.AspNetCore.Mvc;.

   [ApiController] 
   public class ExampleController : Controller 
   { 
   }
Enter fullscreen mode Exit fullscreen mode

Now we only need to create the endpoints for both reading and writing.

  • Creating a GET endpoint in C#

A GET endpoint is used for reading and is very simple. We just need to create a method and decorate this method with either the attributes [HttpGet] to indicate the HTTP method to use along with [Route(“route”)] to indicate the route, or directly [HttpGet(“route”)] that allows us to indicate both the HTTP method and the route that the browser will need to call.

   [HttpGet("name/{id}")] 
   public string ReadName(int id) 
   { 
       return id switch 
       { 
           1 => "Adri", 
           2 => "Codú", 
           _ => throw new System.NotImplementedException() 
       }; 
   }
Enter fullscreen mode Exit fullscreen mode

As we can see, we can indicate variables in the route using brackets.

And later, we will call the endpoint with the browser https://localhost:44380/name/1.

  • Creating a POST endpoint in C#

We use a POST endpoint to update data. We define the route the same way as in the case of GET, but unlike GET, we must send information in the message body.

Of course, without forgetting that we must indicate the attribute as [HttpPost(“route”)].

   [HttpPost("insertemployee")] 
   public int InsertEmployee(Employee employee) 
   { 
       // Code to insert employee into the database 
       return 1; 
   }

   public class Employee 
   { 
       public string Name { get; set; } 
       public string Lastname { get; set; } 
   }
Enter fullscreen mode Exit fullscreen mode

This information will be an object that we can send in either JSON or XML format, and to send it, we can use any application that allows us to send messages over the HTTP protocol, but the most common is Postman.

We need to configure the application a bit, specifying the following points:

  • HTTP method.
  • Destination URL.
  • Body in raw format, and indicate that it is JSON.
  • The body itself.
  • Ensure that in the headers, we have the Content-Type as application/json.
  • Finally, after sending the request, we can see the result in the body section of the response.

  • Other scenarios

For the rest of the scenarios, it's the same, we just need to change the method as desired and the message body.

Others

Before finishing, I want to mention another point, and it is very common to use the name of the controller as part of the URL. As we saw in the previous example, this is not 100% obligatory, but it is a common practice.

To use the controller as part of the URL, we don't have to modify each of our methods to add the controller, but the class itself has its decorator to which we can indicate the route with [Route("[controller]")], where controller is the actual word "controller," not the name of that controller, although obviously, we can modify it.

   [ApiController] 
   [Route("[Controller]")] 
   public class ExampleController : Controller 
   { 
       // Methods  
   }
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding what an API is essential in today's work environment.

We work with APIs all the time, either because our architecture is microservices-based

or because we consume or provide API services.

Knowing the differences between SOAP and REST can make a significant difference in terms of design.

Using APIs also aids development since, as a general rule, the code is smaller, making it easier to test and fix bugs if they occur.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .