Organize Your Web API In A More Convenient Way With API Endpoints In ASP.NET Core

Organize Your Web API In A More Convenient Way With API Endpoints In ASP.NET Core

ยท

2 min read

Why API Endpoints

API Endpoints Is A Way Of Organizing Your Code In An API. In This Approach, You Will Create A Specific Endpoint Class Instead Of A Controller Class Which Is A Lot Better Approach IMO.

API Endpoints In ASP.NET Core

Here's An Example Of A Controller Doing CRUD Operations For A Model Customer

[ApiController]
[Route("Api/[controller]")]
public class CustomersController
{
    private readonly CustomersService _customersService;

    public CustomersController(CustomersService customerService)
    {
        _customersService = customerService;
    }

    [HttpGet]
    public IEnumerable<Customer> GetAll()
    {
        return _customersService.GetCustomers();
    }

    [HttpGet("{id}")]
    public Customer GetOne(int id)
    {
        return _customersService.GetCustomer(id);
    }

    [HttpPost]
    public Customer Create([FromBody] Customer customer)
    {
        return _customersService.AddCustomer(customer);
    }

    [HttpPut("{id}")]
    public Customer Update(int id, [FromBody] Customer customer)
    {
        return _customersService.UpdateCustomer(id, customer);
    }

    [HttpDelete("{id}")]
    public Customer Delete(int id)
    {
        return _customersService.DeleteCustomer(id);
    }
}

This Is Actually A Pretty Simple Example In Real World Scenarios You Will Doing Logging, You Will Be Using MediatR Or You Might Be Injection Services That Are Not Used By Your Whole Controller. That's Where Your Controller Becomes Overwhelming.

Now Here's An Example For A Specific API Endpoint To Get All Customers

public class GetCustomersEndpoint : EndpointBaseSync
    .WithoutRequest
    .WithActionResult<Customer[]>
{
    private readonly CustomersService _customersService;

    public GetCustomersEndpoint(CustomersService customersService)
    {
        _customersService = customersService;
    }

    [EndpointGroupName("Customers")]
    [HttpGet("/Api/Customers")]
    public override ActionResult<Customer[]> Handle()
    {
        return Ok(_customersService.GetCustomers());
    }
}

As You Can See It's More Specific To Get All Customers And That's Where API Endpoints Really Shines.

If You Want To Check The Whole Solution That Contains Both Web APIs Projects WithControllers And WithApiEndpoints Checkout The Complete GitHub Repo

Did you find this article valuable?

Support ProgrammingFire ๐Ÿš€ Blog by becoming a sponsor. Any amount is appreciated!

ย