ASP.NET Core Web API Interview Question #25

What are best practices for designing basic ASP.NET Core Web API endpoints?

Web API & REST Fundamentals, Controllers, HTTP Methods & Status Codes Junior Beginner

Quick Interview Answer

Model endpoints around clear resources and use HTTP methods and status codes consistently. Use attribute routing, API controllers, request and response DTOs, server-side validation, asynchronous I/O, cancellation tokens, and appropriate authentication and authorization.

Detailed Explanation

Model endpoints around clear resources and use HTTP methods and status codes consistently. Use attribute routing, API controllers, request and response DTOs, server-side validation, asynchronous I/O, cancellation tokens, and appropriate authentication and authorization.

Keep controllers focused on HTTP orchestration and move business workflows into application services. Return predictable error contracts, avoid exposing persistence entities or sensitive implementation details, and design the API contract for clients rather than mirroring the database schema.

Code Example

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    [HttpGet("{id:int}")]
    public async Task<ActionResult<ProductResponse>> Get(
        int id,
        CancellationToken token)
    {
        var product = await _service.GetAsync(id, token);

        if (product == null)
            return NotFound();

        return Ok(product);
    }
}