LESSON 10 OF 16

10. CRUD Endpoints and HTTP Response Management

Build list, detail, create, update, and delete endpoints for a product resource. Learn how to select HTTP status codes, shape response bodies, and return consistent validation and error responses.

45 dk 88

Introduction

In the previous lesson, we examined ASP.NET Core Web API controllers and the fundamentals of endpoint design. In this lesson, we will turn the controller layer into a complete CRUD workflow. CRUD stands for Create, Read, Update, and Delete. We will implement these operations for a product resource.

The goal is not simply to write actions that appear to work. A production API must clearly define which HTTP status code is returned for each outcome, what the response body contains, and how errors are represented so that clients can process them reliably. The controller will call the service layer developed earlier and translate application results into HTTP responses instead of containing business rules itself.

A well-designed API makes unsuccessful outcomes as predictable as successful ones.

Mapping CRUD operations to HTTP

With a REST-oriented design, endpoints are usually organized around a resource collection. For products, the collection can be represented by /api/products. A single product is represented by /api/products/{id}.

OperationHTTP methodAddressSuccessful response
ListGET/api/products200 OK
DetailGET/api/products/{id}200 OK
CreatePOST/api/products201 Created
UpdatePUT/api/products/{id}204 No Content or 200 OK
DeleteDELETE/api/products/{id}204 No Content

GET operations read resources. POST creates a new resource. PUT can replace the representation associated with a particular identifier. DELETE removes a resource. If partial updates are required, PATCH can be considered later, but its field-level semantics should be explicitly defined.

Choosing an action result type

ActionResult<T> is a practical choice for most CRUD actions. It communicates the success type while still allowing the action to return results such as NotFound(), BadRequest(), or Conflict().

[ApiController]
[Route("api/[controller]")]
public sealed class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }
}

The [ApiController] attribute enables API-friendly model binding and validation behavior. When model validation fails, the framework can automatically produce a 400 response. However, the controller still needs to make explicit and consistent decisions about results returned by the business layer.

Creating the list endpoint

Let us first create an endpoint that returns all products. Assume that the service layer returns a read-only collection of list DTOs.

[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<ProductListDto>>> GetAll(
    CancellationToken cancellationToken)
{
    var products = await _productService.GetAllAsync(cancellationToken);
    return Ok(products);
}

For a successful GET request, 200 OK is appropriate. The response body is commonly a JSON array. If the collection contains no records, most collection endpoints return an empty array. This is not an error: [] communicates that the collection exists but currently has no items. Returning 404 for an empty collection often forces clients to implement unnecessary special cases.

Retrieving a detail and returning 404

When a client requests one product, the service may not find a matching record. In that case, the API should return 404 Not Found instead of returning a successful 200 response with a null or misleading empty object.

[HttpGet("{id:int}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<ProductDetailDto>> GetById(
    int id,
    CancellationToken cancellationToken)
{
    var product = await _productService.GetByIdAsync(id, cancellationToken);

    if (product is null)
    {
        return NotFound();
    }

    return Ok(product);
}

The {id:int} route constraint prevents non-numeric values from reaching this action. Rules such as requiring a positive identifier can be handled through shared validation or the service layer. The controller's responsibility is to translate a missing result into a 404 response.

Creating a resource with 201 Created

A POST action should accept a create DTO rather than an entity. This limits the fields that clients are allowed to submit. The service creates the record and returns the resulting detail DTO.

[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<ActionResult<ProductDetailDto>> Create(
    [FromBody] CreateProductDto request,
    CancellationToken cancellationToken)
{
    var result = await _productService.CreateAsync(request, cancellationToken);

    if (result.IsDuplicate)
    {
        return Conflict(new { message = "A product with this name already exists." });
    }

    var product = result.Product!;

    return CreatedAtAction(
        nameof(GetById),
        new { id = product.Id },
        product);
}

CreatedAtAction returns 201 Created and builds a Location header pointing to the endpoint that can retrieve the new resource. Returning the created representation in the body also allows the client to use the generated identifier immediately. Although returning 200 with Ok() may work technically, 201 communicates the creation semantics more accurately.

Building the update endpoint

To avoid ambiguity between an identifier in the URL and one in the request body, take the identifier from the route parameter. The update DTO should contain only fields that are allowed to change.

[HttpPut("{id:int}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(
    int id,
    [FromBody] UpdateProductDto request,
    CancellationToken cancellationToken)
{
    var updated = await _productService.UpdateAsync(
        id, request, cancellationToken);

    if (!updated)
    {
        return NotFound();
    }

    return NoContent();
}

Returning 204 No Content after a successful update is useful when the client does not need the updated object immediately. If the client needs the new representation, return Ok(updatedProduct) with 200 instead. The important point is consistency. PUT is generally expected to be idempotent: sending the same complete update twice should lead to the same final state.

Building the delete endpoint

[HttpDelete("{id:int}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(
    int id,
    CancellationToken cancellationToken)
{
    var deleted = await _productService.DeleteAsync(id, cancellationToken);

    if (!deleted)
    {
        return NotFound();
    }

    return NoContent();
}

A successful DELETE can return 204 to indicate completion without a response body. If the target does not exist, the service returns false and the controller returns 404. Some APIs intentionally return 204 whether or not the resource existed, for example to reduce information disclosure or to emphasize idempotent behavior. Whichever policy is selected should be documented and applied consistently.

Designing error responses

An error should not consist only of a numeric status code. Clients often need a title, a human-readable explanation, field-level validation details, and a trace identifier for support diagnostics. ASP.NET Core API controllers can represent errors using ProblemDetails and validation problem responses.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddProblemDetails();

var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();
app.MapControllers();

app.Run();

Unexpected exceptions should never be returned as stack traces to clients. In production, expose a general 500 response and keep diagnostic details in application logs. For known business or validation failures, use Problem() or ValidationProblem() when a structured error is needed.

if (request.Price <= 0)
{
    ModelState.AddModelError(nameof(request.Price),
        "Price must be greater than zero.");

    return ValidationProblem(ModelState);
}

A practical status code policy can be summarized as follows:

  • 400 Bad Request: The request body, model, or client input is invalid.
  • 404 Not Found: The requested resource does not exist.
  • 409 Conflict: The operation conflicts with a uniqueness or concurrency rule.
  • 422 Unprocessable Content: The request is syntactically valid but cannot be processed under the business rules, if this status is part of the team standard.
  • 500 Internal Server Error: An unexpected server failure occurred and the client cannot correct it.

Making the response contract explicit

Use ProducesResponseType to describe possible responses in OpenAPI documentation. Declaring both the successful DTO and the error response type helps client developers understand the contract before sending requests.

[ProducesResponseType<ProductDetailDto>(
    StatusCodes.Status200OK,
    "application/json")]
[ProducesResponseType<ProblemDetails>(
    StatusCodes.Status404NotFound,
    "application/problem+json")]

Do not expose database entities unnecessarily. Passwords, internal notes, audit fields, and database-specific implementation details should not appear in public DTOs. Similarly, avoid returning one unpredictable error shape for every failure. A stable success format and a stable problem format make web clients easier to build and maintain.

Common mistakes

  • Returning Ok() for every outcome and losing the meaning of 404, 201, or 204.
  • Accepting an entity directly from the request body and allowing clients to change protected fields.
  • Failing to identify the newly created resource after POST.
  • Treating an empty collection as a 404 error.
  • Sending exception messages, stack traces, or SQL details in production responses.
  • Calling the repository directly from the controller and bypassing the business layer.
  • Using PUT for partial updates without defining how omitted fields are handled.
  • Ignoring cancellation tokens or returning 200 without checking the service result.

Short practice exercise

Extend your Products controller with the following behavior:

  1. Return 200 and [] for an empty response from GET /api/products.
  2. Return 404 when GET /api/products/999 cannot find a product.
  3. Return 201, a response body, and a Location header for a valid POST request.
  4. Prevent duplicate product names in the service layer and return 409 from the controller.
  5. Return 404 for a missing record and 204 for a successful PUT or DELETE.
  6. Verify that error bodies use the ProblemDetails format.

Use Swagger UI, Postman, or curl to test more than the status code. Inspect response headers, the content type, and the JSON body as well.

Conclusion

In this lesson, we implemented resource-oriented CRUD endpoints and translated service results into meaningful HTTP responses. We saw that 200, 201, 204, 400, 404, 409, and 500 should be selected according to the outcome rather than used arbitrarily. ActionResult<T>, CreatedAtAction, NoContent, and ProblemDetails make the API contract clearer and more predictable for clients.

In the next stage, we will call these endpoints from the web application, process JSON responses, and present API results in the user interface.

Official resources: ASP.NET Core action return types, ASP.NET Core API error handling, and controller-based Web API tutorial.

Sources