Nouman Rahman
ProgrammingFire

ProgrammingFire

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

Nouman Rahman's photo
Nouman Rahman
·Mar 18, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Why API Endpoints
  • API Endpoints In ASP.NET Core

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 Nouman Rahman by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this