LESSON 2 OF 18

2. REST Principles and Resource-Oriented Endpoint Design

Learn REST fundamentals, resource and relationship modeling, plural endpoint naming, and controller-based routing in ASP.NET Core through a practical example.

45 dk 86

Introduction

In the first lesson, we established the project foundation. In this lesson, we will design how our API is exposed to the outside world. A professional API requires more than controllers that happen to work. It needs a resource and endpoint model that clients can understand, predict, and use over the long term.

Our example domain is an e-commerce API. It will contain four primary resources: Products, Categories, Customers, and Orders. We will first examine the central ideas behind REST, then model resources and their relationships, and finally create controller and route structures in ASP.NET Core.

REST does not mean exposing application classes or database tables directly. The important task is to identify the conceptual resources that clients need and transfer representations of those resources consistently over HTTP.

Fundamental REST principles

Think in resources

In a REST-oriented design, the primary question is not “Which operations should become endpoints?” It is “Which resources exist in the system?” A product, category, customer, or order is a resource. Resources are identified by URIs, while HTTP methods express standard operations against those resources.

ResourceCollection URIIndividual resource URI
Products/api/products/api/products/42
Categories/api/categories/api/categories/3
Customers/api/customers/api/customers/18
Orders/api/orders/api/orders/1005

/api/products represents a product collection, while /api/products/42 represents the product whose identifier is 42. Verbs in URIs are usually unnecessary. Prefer GET /api/products and POST /api/orders over paths such as /api/getProducts or /api/createOrder.

Client-server separation

The client and server have different responsibilities. The client manages the user interface and interaction flow. The server manages resources, business rules, and data. This separation allows the same API to serve a web application, a mobile application, or another service.

Stateless communication

Each HTTP request should contain the information required to process it whenever possible. The server should not depend on temporary state from a previous request. For example, a customer identity or authorization decision should not be inferred merely because it appeared in an earlier request. Authentication information and relevant parameters must be evaluated in the context of each request.

Uniform interface

One of REST’s most useful properties is predictability. Similar operations should use consistent combinations of methods, URIs, and response semantics. Therefore, listing products is represented by GET /api/products, reading one product by GET /api/products/{id}, and creating a product by POST /api/products.

Representations and HTTP

A client does not access a database row directly. It receives or sends a representation of a resource, commonly JSON. A product representation does not need to expose every database column. Keeping this distinction clear is important for DTOs and for protecting the API contract when the internal data model changes.

Modeling resources and relationships

Before creating routes, consider the domain model. A category can contain many products. A customer can place many orders. An order belongs to one customer and contains multiple order items.

  • Category → Products: one-to-many relationship.
  • Customer → Orders: one-to-many relationship.
  • Order → OrderItems: one-to-many relationship.
  • Product → OrderItems: a product can appear in many orders.

There is no single mandatory way to expose these relationships. Direct access to general collections can use /api/products and /api/orders. When a relationship-specific view is useful, a nested route may be appropriate:

  • GET /api/categories/3/products
  • GET /api/customers/18/orders
  • GET /api/orders/1005/items

Unlimited nesting reduces readability. Instead of a path such as /api/customers/18/orders/1005/items/2/product, prefer a direct resource URI such as /api/orders/1005/items/2 or /api/products/42 when that better represents the client’s goal.

Mapping HTTP methods to resources

OperationHTTP methodExample route
List productsGET/api/products
Read one productGET/api/products/42
Create a productPOST/api/products
Replace a productPUT/api/products/42
Partially update a productPATCH/api/products/42
Delete a productDELETE/api/products/42

This lesson focuses primarily on route structure. The detailed behavior of HTTP methods and status codes will be covered more deeply in later lessons. However, preserving this mapping from the beginning prevents inconsistent API design.

Creating controllers and routes in ASP.NET Core

Configure Program.cs

Register controller services and map controller endpoints:

var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddOpenApi(); var app = builder.Build(); if (app.Environment.IsDevelopment()) {    app.MapOpenApi(); } app.UseHttpsRedirection(); app.MapControllers(); app.Run();

AddControllers registers controller services in the dependency injection container. MapControllers adds actions that use attribute routing to the application’s endpoint table. Without MapControllers, controller classes may compile but their routes will not be mapped.

ProductsController

Let the first controller represent the product collection:

using Microsoft.AspNetCore.Mvc; namespace Store.Api.Controllers; [ApiController] [Route("api/[controller]")] public sealed class ProductsController : ControllerBase {    [HttpGet]    public ActionResult<IReadOnlyCollection<object>> GetAll()    {        var products = new[]        {            new { Id = 1, Name = "Keyboard", Price = 79.90m },            new { Id = 2, Name = "Mouse", Price = 29.90m }        };        return Ok(products);    }    [HttpGet("{id:int}")]    public ActionResult<object> GetById(int id)    {        if (id <= 0)        {            return NotFound();        }        return Ok(new { Id = id, Name = "Keyboard", Price = 79.90m });    } }

In [Route("api/[controller]")], the [controller] token is replaced with the controller name without the Controller suffix. Therefore, ProductsController produces the base route /api/products. ASP.NET Core route matching is case-insensitive, but consistent lowercase paths are generally easier for clients and documentation to read.

{id:int} is a route constraint. It allows the route to match only integer identifiers. A request such as /api/products/abc will not be selected for the same action.

Other controllers

The same basic structure can be applied to the other resources:

[ApiController] [Route("api/[controller]")] public sealed class CategoriesController : ControllerBase {    [HttpGet]    public IActionResult GetAll() => Ok(); } [ApiController] [Route("api/[controller]")] public sealed class CustomersController : ControllerBase {    [HttpGet("{id:int}/orders")]    public IActionResult GetOrders(int id) => Ok(); } [ApiController] [Route("api/[controller]")] public sealed class OrdersController : ControllerBase {    [HttpGet]    public IActionResult GetAll() => Ok(); }

The purpose of these examples is to establish the external resource contract, not to complete data access. In a real project, controllers should generally delegate to an application or service layer rather than execute database queries directly.

Common route design mistakes

  • Verb-based URIs: Paths such as /api/getProducts, /api/createOrder, and /api/deleteCustomer repeat the meaning already expressed by HTTP methods.
  • Singular collection names: Use /api/products for a collection instead of /api/product to make the distinction clearer.
  • Exposing database tables directly: A database table name and an API resource name do not need to be identical. The API contract should evolve independently from the persistence model.
  • Excessive nesting: Long URIs make client code harder to use. Choose the nearest meaningful resource.
  • Ambiguous action routes: Actions with overlapping templates can conflict. Use explicit templates and route constraints.
  • One controller for everything: Separating product, customer, and order responsibilities improves readability and maintainability.

Short practice exercise

Complete the following exercise:

  1. Create ProductsController, CategoriesController, CustomersController, and OrdersController.
  2. Define a plural base route for each controller.
  3. Add a collection-listing action to every controller.
  4. Add individual-resource actions using {id:int} for Products and Orders.
  5. Add GET /api/customers/{id}/orders to the Customers controller.
  6. Run the application and test GET /api/products, GET /api/products/1, and GET /api/customers/5/orders.

Also answer this question: For retrieving products in a category, is /api/products/by-category/3 or /api/categories/3/products more resource-oriented? Consider the purpose of each design and justify your choice.

Conclusion

This lesson introduced the resource-oriented way of thinking that forms the foundation of REST design. We defined Products, Categories, Customers, and Orders using plural resource names; distinguished collection and individual-resource URIs; represented relationships with nested routes when appropriate; and configured controller-based attribute routing in ASP.NET Core.

A good endpoint design influences every later API decision. DTOs, validation, pagination, and error handling will be built on top of this foundation. Therefore, routes should not be treated as temporary URLs. They should be designed as a long-lived API contract shared with client applications.

Sources