Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 13

    REST API Design in ASP.NET Core: Resources, HTTP Methods and Status Codes

    What this lesson teaches

    REST API design in ASP.NET Core starts with resources, HTTP methods and clear status codes. Learn how to design an orders API and explain your choices.

    By the end, you can choose an order URL, distinguish PUT from PATCH, return meaningful status codes and explain why database entities should not cross the API boundary. The API boundary is the line between your service's code and the clients that call it over HTTP.

    What makes an API RESTful?

    REST means Representational State Transfer. It is an architectural style: a set of constraints for how clients and servers interact.

    REST is defined by a few constraints: client-server, stateless requests, cacheable responses, a uniform interface and a layered system. Code on demand is an optional constraint: a server can supply code for the client to run.

    Client-server separates the client's responsibilities from the server's. Stateless requests each carry all the information the server needs to understand them; the server keeps no client session between requests. Cacheable responses indicate whether their data can be reused for later requests. A uniform interface gives clients consistent rules for identifying and interacting with resources. A layered system allows intermediaries between the client and the server.

    Web APIs apply REST through HTTP. Resources have URLs, representations describe their data, standard methods express operations, and response links guide clients to available actions. We will unpack these ideas below.

    The mistake to avoid. JSON and noun-based URLs alone do not make an API RESTful. REST describes how the whole interaction is designed.

    In an interview, say: “REST has client-server, statelessness, cacheability, a uniform interface and layered-system constraints, with optional code on demand. Over HTTP, we use resource URLs, representations, standard methods and links. Most everyday REST-style APIs stop at Richardson level 2 rather than implementing every constraint.”

    For HTTP safety, idempotency and headers, use the prerequisite lesson on HTTP methods, status codes, headers and redirects. We apply those rules here rather than teach them again.

    Start with resources, not database tables

    A resource is something your API makes available, such as an order or a collection of orders. Its URL identifies it. A representation is the data sent to describe that resource, usually JSON in these examples.

    Use plural nouns for collections:

    URLMeaning
    /ordersThe orders collection
    /orders/42One order
    /orders/42/itemsThat order's items collection

    Prefer /orders over /createOrder. The HTTP method already supplies the action.

    Keep paths shallow. For this API, stop at collection/item/collection. Instead of extending a path through customers, orders, items and products, give independently useful resources their own URLs. This is a design guideline, not a REST validity test.

    flowchart TD
        U["/orders/42"] -->|identifies| O["Order 42"]
        O -->|is described by| J["JSON order representation"]

    The URL identifies the order; the JSON describes it without exposing how it is stored.

    A contract is the request and response structure clients can rely on. Design that contract around business needs, not as a copy of database tables.

    Use separate request and response data transfer objects (DTOs) rather than accepting or returning EF entities. For example, a create request can accept Product, while the response includes a server-assigned Id and Status.

    A narrow request DTO also stops over-posting: a client cannot set isApproved or price when the DTO has no such property. It does not replace permission checks. JSON contracts and DTOs shows over-posting in code.

    The mistake to avoid. Do not expose an EF entity merely because it already has convenient properties. Changes to your database classes can then break clients. You might also expose hidden data or let clients change properties they should not control.

    In an interview, say: “I model business resources with noun-based URLs and plural collections. DTOs cross the API boundary, not EF entities. Separate request and response DTOs limit writable data, avoid leaks and keep the contract stable when storage changes.”

    Microsoft's web API design guidance explains resource naming and collection relationships.

    Choose the method from the intent

    Choose the HTTP method before writing the method that handles the request (the handler):

    MethodIntentOrders example
    GETRead a representationGET /orders/42
    POSTCreate under a collection, or request processingPOST /orders
    PUTCreate or replace at a known URLPUT /orders/42
    PATCHApply a partial changePATCH /orders/42 with an allowed address change
    DELETERemove the resourceDELETE /orders/42

    For PUT, the client supplies the replacement representation defined by the contract. It does not mean overwriting every internal database column.

    Some business operations do not fit simple create, read, update and delete operations, often called CRUD. Cancelling an order is one example.

    We will use POST /orders/42/cancel. Here, cancellation is a business operation that checks the current order state. It is an intentional action-style exception to noun-based resource naming.

    PATCH /orders/42 with a status change is another possible contract. Choose it when clients really are editing an allowed property. For this API, POST makes the business operation clearer and avoids suggesting that clients may freely assign any status.

    The trade-off is an extra operation URL. POST also does not promise idempotency just because this particular cancellation implementation might tolerate retries.

    The mistake to avoid. Do not treat PUT as “update whatever properties were supplied.” That describes a partial change, while PUT communicates replacement at the target URL.

    In an interview, say: “PUT replaces at a known URL and is idempotent. POST creates under a collection or requests processing. PATCH applies a partial change. I would use POST for order cancellation because it runs a business operation, rather than allowing arbitrary status editing.”

    Make the status code describe the outcome

    The status code lets a client understand the outcome without interpreting application-specific JSON first. Choose it from what happened, not merely whether the handler finished running.

    OutcomeResponse
    Read succeeded200 OK, with the representation
    Resource created201 Created, with Location identifying the new resource
    Work accepted but not completed202 Accepted; provide a way to check progress (see long-running operations)
    Operation succeeded with no response body204 No Content
    Bad input400 Bad Request
    Item not found404 Not Found
    Current business state prevents the operation409 Conflict
    Unsupported request body format415 Unsupported Media Type
    No valid credentials401 Unauthorized
    Caller is authenticated but not allowed403 Forbidden
    Unexpected server failure500 Internal Server Error

    Location identifies where the created resource can be found. It may be relative: /orders/1 is valid here.

    Some APIs document 422 Unprocessable Content for input that is understood but fails validation rules. Consistency matters: clients should not have to guess between 400 and 422.

    A shipped order that cannot be cancelled is a 409, not a missing order. An expected business conflict should not become a 500.

    The mistake to avoid. Never return 200 OK with an error hidden inside the body. Clients, monitoring and other HTTP-aware tools can otherwise interpret the request as successful.

    In an interview, say: “For creation I return 201 with Location. For a successful delete with no body, 204. Bad input gets 400, or a documented 422 policy. A missing item gets 404, and a conflict with current business state gets 409.”

    Distinguish identity from permission

    Credentials are the evidence supplied to establish identity, such as an access token.

    A tenant is a customer or organization whose data must be separated from other customers' data. In a system serving multiple tenants, an order may exist but belong to another tenant.

    If even revealing that order's existence would disclose information, return 404 to that caller. Apply this policy consistently, and check tenant access before returning the order data.

    The mistake to avoid. Do not return 403 merely because credentials are missing. Also, do not reveal another tenant's resource just to give a more specific error.

    In an interview, say: “401 means there are no valid credentials. 403 means the caller is authenticated but not allowed. I may return 404 instead when the caller must not learn that another tenant's item exists.”

    See the orders API in code

    A Minimal API defines HTTP handlers directly through methods such as MapGet and MapPost. An endpoint is an operation clients reach through a method and URL. Microsoft's APIs overview compares Minimal APIs with controller-based APIs.

    This .NET 10 example uses TestServer, ASP.NET Core's in-memory test server. Its HttpClient sends requests through the application without opening a port or using the network.

    TypedResults and Results<T1, T2> declare each handler's possible responses; Minimal APIs vs controllers explains them.

    Run this example in a web project (Microsoft.NET.Sdk.Web) that has the Microsoft.AspNetCore.TestHost package installed. Microsoft.AspNetCore.Mvc.Testing also brings that package in.

    Before running, predict the status for each request. One order, number 42, starts as shipped. The newly created order gets number 1.

    C#
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Http.HttpResults;
    using Microsoft.AspNetCore.TestHost;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using System.Net.Http.Json;
    
    var builder = WebApplication.CreateBuilder(args);
    builder.WebHost.UseTestServer();
    builder.Logging.ClearProviders();
    await using var app = builder.Build();
    
    var orders = new Dictionary<int, OrderDto>
    {
        [42] = new(42, "Keyboard", "Shipped")
    };
    var nextId = 1;
    
    app.MapPost("/orders", Create);
    app.MapGet("/orders/{id:int}", Read);
    app.MapPost("/orders/{id:int}/cancel", Cancel);
    app.MapDelete("/orders/{id:int}", Delete);
    
    Results<Created<OrderDto>, BadRequest<string>> Create(CreateOrderDto request)
    {
        if (string.IsNullOrWhiteSpace(request.Product))
            return TypedResults.BadRequest("Product is required.");
    
        var order = new OrderDto(nextId++, request.Product, "Pending");
        orders.Add(order.Id, order);
        return TypedResults.Created($"/orders/{order.Id}", order);
    }
    
    Results<Ok<OrderDto>, NotFound> Read(int id)
    {
        if (!orders.TryGetValue(id, out var order))
            return TypedResults.NotFound();
        return TypedResults.Ok(order);
    }
    
    Results<NoContent, NotFound, Conflict<string>> Cancel(int id)
    {
        if (!orders.TryGetValue(id, out var order))
            return TypedResults.NotFound();
        if (order.Status == "Shipped")
            return TypedResults.Conflict("A shipped order cannot be cancelled.");
    
        orders[id] = new OrderDto(order.Id, order.Product, "Cancelled");
        return TypedResults.NoContent();
    }
    
    Results<NoContent, NotFound> Delete(int id)
    {
        if (!orders.Remove(id))
            return TypedResults.NotFound();
        return TypedResults.NoContent();
    }
    
    await app.StartAsync();
    using var client = app.GetTestClient();
    
    Show("POST /orders", await client.PostAsJsonAsync(
        "/orders", new CreateOrderDto("Mouse")));
    Show("GET /orders/1", await client.GetAsync("/orders/1"));
    Show("POST /orders/42/cancel", await client.PostAsync(
        "/orders/42/cancel", null));
    Show("DELETE /orders/1", await client.DeleteAsync("/orders/1"));
    Show("GET /orders/1", await client.GetAsync("/orders/1"));
    Show("DELETE /orders/1 again", await client.DeleteAsync("/orders/1"));
    
    static void Show(string request, HttpResponseMessage response)
    {
        using (response)
        {
            Console.WriteLine($"{request}: {(int)response.StatusCode}");
            if (response.Headers.Location is { } location)
                Console.WriteLine($"Location: {location}");
        }
    }
    
    public record CreateOrderDto(string Product);
    public record OrderDto(int Id, string Product, string Status);
    Output
    POST /orders: 201
    Location: /orders/1
    GET /orders/1: 200
    POST /orders/42/cancel: 409
    DELETE /orders/1: 204
    GET /orders/1: 404
    DELETE /orders/1 again: 404

    Needs ASP.NET Core (a web project) and the package Microsoft.AspNetCore.Mvc.Testing 10.0.12. Built and run on the in-memory TestServer: the output above is what it printed.

    Follow the requests in order:

    1. Create: Create constructs an order from the request DTO. TypedResults.Created supplies 201 and the relative Location /orders/1.
    2. Read: the dictionary contains order 1, so Read returns 200 with its response DTO.
    3. Cancel: order 42 exists, but its shipped state prevents cancellation. The handler returns 409.
    4. Delete: removing order 1 succeeds, so the handler returns 204 without a body.
    5. Read again: order 1 no longer exists, so the response is 404.
    6. Delete again: nothing remains to remove, so this implementation returns 404.

    The dictionary keeps this demonstration small. The data is lost when the program stops, and two requests at the same time could corrupt the dictionary. The example also omits authentication and tenant checks; it demonstrates response choices, not a complete production service.

    You can run this smaller console example without installing packages. It shows what happens to the dictionary during the two deletion attempts; it does not start an HTTP server.

    C#Runs
    var orders = new Dictionary<int, string>
    {
        [1] = "Mouse"
    };
    
    Console.WriteLine($"First removal succeeded: {orders.Remove(1)}");
    Console.WriteLine($"Second removal succeeded: {orders.Remove(1)}");
    Console.WriteLine($"Order 1 still exists: {orders.ContainsKey(1)}");
    Output
    First removal succeeded: True
    Second removal succeeded: False
    Order 1 still exists: False

    The mistake to avoid. Do not change the second DELETE to 204 solely to “make it idempotent.” Either documented response policy can preserve the same intended effect.

    In an interview, say: “A repeated DELETE may return 404 after the first returns 204. It is still idempotent because repeating it leaves the resource absent. Idempotency describes the intended effect, not identical responses.”

    Check yourself

    An order exists, but it has already shipped and cannot be cancelled. Which response best describes this outcome?

    A 200 OK with an error property
    B 404 Not Found
    C 409 Conflict
    D 500 Internal Server Error
    Show answer

    Correct answer: C

    The order exists, but its current business state conflicts with the cancellation request.

    DELETE /orders/1 returns 204. Repeating it returns 404. Is the operation still idempotent?

    A No, because the two calls return different status codes
    B Yes, because both calls leave order 1 absent
    C Only if both responses carry the same JSON body
    D Only if the client repeats it with PUT instead
    Show answer

    Correct answer: B

    Idempotency concerns the intended effect of repeating a request, not identical response codes.

    Richardson maturity model and HATEOAS

    The Richardson maturity model describes four levels of HTTP API design:

    • Level 0: HTTP carries operation calls, often through one URL.
    • Level 1: distinct resources have distinct URLs.
    • Level 2: HTTP methods and status codes express the operations and outcomes. This is where most everyday REST-style APIs sit.
    • Level 3: responses include links that guide clients to available next actions.

    HATEOAS means Hypermedia as the Engine of Application State. The response contains links to the next actions the client can take, such as a “cancel” link, so the client does not hard-code those URLs. There is no single universally adopted HATEOAS response format; clients and servers still need agreed link conventions.

    The mistake to avoid. Do not call an API level 3 merely because it uses JSON. Level 3 adds links that guide the client's next actions.

    In an interview, say: “Richardson has four levels: operation calls, resource URLs, HTTP methods and status codes, then hypermedia links. Most everyday REST-style APIs are level 2. HATEOAS uses response links to guide the client's next actions, but it has no single universally adopted response format.”

    Going deeper

    For the wider architectural choice, including gRPC, a framework for calling remote service methods, continue with API design, REST, pagination, versioning and gRPC.

    Sources

    Practice

    Practice test: Practice: REST API Design in ASP.NET Core: Resources, HTTP Methods and Status Codes8 questions · 1 mark each, no negative markingFull Access
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·