REST API in C#

 

With times changing, companies, thankfully, no longer build one gigantic application that does everything; instead, that same application is divided into different modules or smaller projects, each performing a specific function.

We call the use of small projects to assemble a larger application microservice architecture, which I will make a video on later. The reason I mention this architecture here is because microservices rely on or are based on APIs.

 

1 - What is an API?

There are several ways to define what an API is. Personally, I define it as follows: An API is the entry point from the outside into your project.

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

api architecture

As we can see in the image, we have our front end, which consumes the back end through an API, and in turn, the back end consumes two other services via APIs.

An API can return something as small as a single character, or a list containing thousands of elements.

 

2 - Types of API in C#

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

Both options have different features, but the ultimate goal is the same: to send information between a client and a server.

2.1 - Differences between SOAP and REST

There are many differences, enough for a whole post, but I’ll list what I think are the most important:

A - Protocol

A major difference is that SOAP is a protocol while REST is an architecture that works over the HTTP protocol.

B - Development

Developing a SOAP service requires more time for both the client and the server, since we need to create a .wsdl file, which is an XML containing the data needed and where the web service is located. The `.wsdl` format also allows us to add a dtd which can validate all fields of the xml before sending the message.

 

On the other hand, REST works over the HTTP protocol, which means to receive/send information we must do so via web requests, through the URL or by using the message body. For the message body, we use Json or XML. But unlike SOAP, all validations happen on the server side.

For these reasons, developing a REST API is much faster than developing a SOAP web service.

Of course, SOAP has advantages in other areas. For example, it can maintain state across multiple requests, while in REST each request is independent.

And due to the previously mentioned point about the wsdl file with xml and dtd, SOAP services are much more secure.

 

3 - Creating an API in C#

Creating a REST API in C# is very simple; you just have to create a new web project.

For the type, choose API. You can pick empty, web application or even web application (MVC). The only difference is the amount of default functionalities included.

For the example, I chose an empty project.

 

Before going further, in NetCore we have middleware that allows us to configure endpoints in the startup.cs class, but for now we’ll "ignore" it since it’s a more advanced topic.

 

When creating APIs, we need to create endpoints with CRUD in mind.

3.1 - What is CRUD?

CRUD is an acronym that refers to:

  • Create (for which we use the HTTP POST method),
  • Read (for which we use HTTP GET),
  • Update (where we use HTTP PUT),
  • Delete (where we use 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, ensure that in the startup.cs class, you have the service that adds controllers:

public void ConfigureServices(IServiceCollection services){    services.AddControllers();}

And in the same class, in the configure method, inside UseEndpoints, you must specify to look for these endpoints in controllers with the condition endpoints.MapControllers():

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

3.2 - Creating the endpoints

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

[ApiController]public class EjemploController : Controller{}

Note: remember controllers must always extend from Controller.

Now, we just have to create the endpoints for both reading and writing.

 

A - Creating a GET endpoint in C#

A GET endpoint is used for reading and is very easy to set up: just create a method, and decorate it with the `[HttpGet]` attribute to indicate the HTTP method to use, along with `[Route("route")]` to indicate the route, or directly [HttpGet("route")] for both the HTTP method and the route that will be called by the browser.

[HttpGet("nombre/{id}")]public string ReadName(int id){    return id switch    {        1 => "Net",        2 => "mentor",        _ => throw new System.NotImplementedException()    };}

As you can see, you can specify variables in the route using brackets.

Then you call the endpoint with the browser: https://localhost:44303/nombre/1

B - Creating a POST endpoint in C#

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

Of course, don’t forget to indicate the attribute as [HttpPost("route")].

[HttpPost("insertarempleado")]public int InsertEmployee(Employee employee){    // Code to insert employee into the database    return 1;}public class Employee{    public string Name { get; set; }    public string Surname { get; set; }}

This information will be an object which we can send in JSON or XML format, and to send it, we can use any application that allows sending messages over HTTP. The most common is postman.

 

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

  1. HTTP method.
  2. Destination URL.
  3. Body in raw format, and specify that it is json.
  4. The body itself.
  5. Make sure the headers include Content-Type as application/json.
  6. Finally, after sending the request, you can see the result in the response body section.

postman example

C - Other scenarios

For other scenarios, the process is the same; we just need to change the method and the body of the message as needed.

 

Others

Before finishing, I want to mention another point: it is very common to use the controller name as part of the URL. As we saw earlier, this is not 100% mandatory, but it is common practice.

To use the controller as part of the url, you do not need to modify each method to add the controller; instead, the class itself has a decorator where you can indicate the route with [Route("[controller]")], where `controller` is the actual word controller (not the name of your controller), though you can, of course, modify it.

[ApiController][Route("[Controller]")]public class EjemploController : Controller{   // methods }

Conclusion

Having a clear understanding of what an API is essential in today's workplace.

We work with APIs all the time, whether because our architecture is based on microservices or because we are consumers or providers of API services.

Knowing how to tell the difference between the features or advantages of SOAP and REST can make a big difference in design decisions.

Using APIs also helps development, as the code is generally smaller, making it easier to test and, if there’s a bug, easier to fix.

Finally, many interviews for mid or senior roles will include a part where you have to either build an API in code or define an API on a whiteboard.

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café