liveBook · Manning

Controller

As explained in Grokking Software Architecture

A controller is an application component that receives requests and coordinates processing between the user interface and application logic.

A controller is a gate-side translator: it turns external HTTP requests into calls to application services, then translates results into HTTP responses. It coordinates communication without making business decisions. section 6.7

Keep its responsibilities narrow:

  • Handle HTTP details such as routes and status codes. section 6.7
  • Delegate business rules and data access to services or other application components. section 6.7
  • Keep the application logic reusable: a different entry point, such as a command-line interface, can call the same service. section 6.7.1

Order lookup

For GET /api/orders/{id}, the controller asks an order service for the requested order, returns a not-found response if it is missing, and otherwise returns the order as JSON. section 6.7

Listing 6.5 An Example of a Clean API Endpoint
[ApiController]
[Route("api/orders")] // The Menu Section
public class OrderController : ControllerBase
{
    private readonly IOrderService _service; // The Core
 
    public OrderController(IOrderService service)
    {
        _service = service;
    }
 
    // THE CONTRACT: GET /api/orders/{id}
    [HttpGet("{id}")]
    public async Task<IActionResult> GetOrder(int id)
    {
        // 1. Translate HTTP request to Domain intent
        var order = await _service.GetOrderById(id);
 
        // 2. Handle "Not Found" (Implicit Contract)
        if (order == null)
            return NotFound($"Order {id} not found.");
 
        // 3. Translate Domain Object to HTTP Response (JSON)
        return Ok(order);
    }
}

Inspect the complete C# endpoint, including its route, service call, and HTTP responses. section 6.7

How Grokking Software Architecture covers it

How deep it goes
Defines the controller as a translator and works through a REST endpoint, leaving business decisions and SQL to other components.
Examples
Uses an order lookup endpoint that delegates to a service and returns either not-found or a JSON response.
What you can do after
Apply it by separating HTTP translation from business decisions and delegating work to a service.
How it connects
Connects controllers to REST APIs, HTTP, services, MVC, and Hexagonal Architecture.

Also explained in

Compare how 13 books explain controller →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Software Architecture. The section links point to the parts of the book it draws on.