Domain-Driven Design (DDD) and REST APIs work best when the API surface maps cleanly to the domain model, not to database tables. You build a REST API by exposing a small set of endpoints that read or write aggregates, where each aggregate is a cluster of related entities and value objects that are guaranteed to be consistent. The API does not expose internal implementation details like repository methods or private fields; instead, it exposes only the operations the domain allows, and it uses HTTP verbs and status codes to express the result. For example, a GET request to /orders/{orderId} returns the current state of that order, while a POST to /orders creates a new order and returns it with a 201 Created status.

To see how this looks in practice, imagine you run an online bakery. The domain model contains an Order aggregate with properties like order number, timestamp, and a list of OrderLine items, each holding a product code and a requested quantity. The REST API exposes only the operations needed for customers and the checkout system: create an order, add an item to an existing order, and retrieve the order details. If a customer tries to add an item to an order that is already paid or delivered, the domain rejects that request, and the API returns a 409 Conflict with a message explaining why. This keeps the API simple and the domain logic in one place.

Pick the Right Structure for Your API

Start by identifying the core aggregates in your domain. An aggregate is a cluster of entities that you treat as a single unit of change. For a bakery, the aggregates might be Order, Product, and Customer. Each aggregate gets its own top-level resource path, such as /orders, /products, and /customers. This makes the API surface match the domain structure and makes it easier to reason about what operations are allowed.

For each aggregate, decide which operations are allowed. A typical pattern is to support these CRUD-style operations: create, read, update, and delete. However, in DDD you should not expose every possible combination of these operations. Instead, expose only the operations that make sense from the domain perspective. For an Order aggregate, you might allow creating an order and reading its details, but you might not allow deleting an order directly. Instead, you might allow a soft delete or a status change to “cancelled”. This keeps the API focused on the domain’s invariants.

When naming your endpoints, use nouns for resources and verbs for actions. For example, use /orders/{id}/items to represent adding an item to an order, rather than using HTTP POST to /orders with a complex body. This keeps the URL structure clear and makes the API self-documenting. You can also use query parameters to filter or paginate results, such as /orders?customer=123&status=paid, but keep these optional and well-documented.

Map Requests to Domain Commands and Queries

When a client sends a request to your API, you must translate that request into a domain command or query. A command is an operation that changes the state of the domain, such as creating an order or adding an item. A query is an operation that reads the state without changing it, such as retrieving an order or listing products. This separation helps you keep your domain logic clean and makes it easier to test.

For example, when a client sends a POST request to /orders with a JSON body like { "customer": 123, "lines": [ { "product": "cake", "quantity": 2 } ] }, your API handler should map this into a CreateOrder command and pass it to the domain service or repository. The domain service then validates the command, creates the order, and persists it. If the command is valid, the API returns a 201 Created response with the created order in the body. If the command is invalid, the API returns a 400 Bad Request with a list of validation errors.

For queries, the process is similar. When a client sends a GET request to /orders/{id}, your API handler maps this into a GetOrder query and passes it to the repository. The repository loads the order from the database and returns it to the handler, which then serializes it to JSON and sends it back in the response. If the order does not exist, the API returns a 404 Not Found response.

Use HTTP Verbs and Status Codes Correctly

HTTP verbs and status codes are part of the REST contract, and using them correctly helps clients understand what happened. Use GET for read operations, POST for creating new resources, PUT for replacing an entire resource, and PATCH for partially updating a resource. Avoid using POST for read operations or GET for write operations; this breaks the REST contract and makes the API confusing.

Status codes should reflect the outcome of the request. A 200 OK response is appropriate when a GET or PUT/PATCH request succeeds. A 201 Created response is appropriate when a POST request creates a new resource. A 204 No Content response is appropriate when a PUT or PATCH request succeeds but does not return a body. A 400 Bad Request response is appropriate when the request is malformed or contains invalid data. A 404 Not Found response is appropriate when the requested resource does not exist. A 409 Conflict response is appropriate when the request cannot be completed due to a conflict with the current state of the resource, such as trying to add an item to a paid order.

Avoid Common Mistakes in DDD REST APIs

One common mistake is to expose the database schema directly through the API. For example, exposing endpoints like /users, /addresses, and /phone_numbers separately can lead to inconsistencies and make it hard to enforce domain invariants. Instead, expose aggregates like /customers, which contain all the related data for a customer. This keeps the API surface aligned with the domain model and makes it easier to enforce invariants.

Another mistake is to use HTTP verbs incorrectly. For example, using POST for read operations or GET for write operations breaks the REST contract and makes the API confusing. Always use GET for read operations and POST for creating new resources. If you need to update a resource, use PUT for replacing the entire resource or PATCH for partially updating the resource.

A third mistake is to ignore domain invariants in the API layer. For example, allowing a client to update an order’s status directly through the API without checking invariants like “an order can only be paid once” can lead to inconsistencies. Instead, expose only the operations that enforce invariants, and let the domain handle the validation. If a client tries to perform an invalid operation, the domain should reject it, and the API should return an appropriate error response.

Create an Order with Items

Let’s walk through a concrete example of creating an order with items in a bakery system. The domain model contains an Order aggregate with properties like order number, timestamp, customer ID, and a list of OrderLine items. The API exposes a POST endpoint at /orders that accepts a JSON body with the order details.

When a client sends a POST request to /orders with the following body:

{
  "customer": 123,
  "lines": [
    { "product": "cake", "quantity": 2 },
    { "product": "bread", "quantity": 1 }
  ]
}

Your API handler should map this into a CreateOrder command and pass it to the domain service. The domain service then validates the command by checking that the customer exists, that the products exist, and that the quantities are positive. If any of these checks fail, the domain service returns a validation error, and the API handler returns a 400 Bad Request response with the errors.

If the command is valid, the domain service creates the order and persists it. The order is assigned a unique order number, such as ORD-001, and the timestamp is set to the current time. The order lines are created with the product codes and quantities from the command. The domain service then returns the created order to the API handler, which serializes it to JSON and sends it back in a 201 Created response.

The response body might look like this:

{
  "orderId": "ORD-001",
  "customer": 123,
  "timestamp": "2023-05-01T12:00:00Z",
  "lines": [
    { "product": "cake", "quantity": 2 },
    { "product": "bread", "quantity": 1 }
  ],
  "total": 15.00
}

The total is calculated by the domain service based on the product prices. This ensures that the calculation is consistent with the domain model and that it is not exposed directly to the client.

What Happens If You Add an Item to a Paid Order?

If you try to add an item to an order that is already paid, the domain will reject that request. The API will receive a POST request to /orders/{id}/items with the item details, but the domain service will check the order’s status. If the status is “paid”, the domain service will return an error, and the API will return a 409 Conflict response with a message explaining why. This keeps the domain invariants intact and prevents the API from returning inconsistent state.

How to Handle Cancellation and Refunds?

For cancellation and refunds, you might expose a POST endpoint at /orders/{id}/cancel that changes the order’s status to “cancelled”. The domain service will check that the order can be cancelled, such as that it has not already been shipped. If the order can be cancelled, the domain service changes the status and returns the updated order. If the order cannot be cancelled, the domain service returns an error, and the API returns a 400 Bad Request response.

How to Retrieve an Order and Its Items?

To retrieve an order and its items, you expose a GET endpoint at /orders/{id}. The API handler maps this into a GetOrder query and passes it to the repository. The repository loads the order from the database and returns it to the handler, which serializes it to JSON and sends it back in a 200 OK response. If the order does not exist, the repository returns null, and the API handler returns a 404 Not Found response.

How to List Orders for a Customer?

To list orders for a customer, you expose a GET endpoint at /customers/{id}/orders with optional query parameters for filtering and pagination. The API handler maps this into a ListOrdersForCustomer query and passes it to the repository. The repository returns a list of orders that match the query, sorted by timestamp in descending order, and the API handler serializes them to JSON and sends them back in a 200 OK response.

What to Check After Every Request?

After every request, you should check that the response is consistent with the domain model. For example, if you create an order and then immediately retrieve it, the order should have the same number of lines, the same quantities, and the same total as you sent in the request. If there is a discrepancy, it indicates a bug in the domain service or the repository. You should also check that the HTTP status code is appropriate for the operation. For example, if you create an order and the domain rejects it, you should return a 400 Bad Request response, not a 201 Created response.

How to Handle Concurrency Conflicts?

If multiple clients try to update the same order at the same time, you might encounter a concurrency conflict. One common approach is to use optimistic locking, where each order has a version number. When a client updates an order, the API handler sends the current version along with the update. The domain service checks that the version in the request matches the version in the database. If they match, the domain service updates the order and increments the version. If they do not match, the domain service returns an error, and the API returns a 409 Conflict response. This allows you to detect and handle concurrency conflicts gracefully.

How to Handle Errors and Validation Messages?

When an error occurs, such as a validation error or a concurrency conflict, you should return a clear and consistent error response. A typical error response might look like this:

{
  "error": "VALIDATION_ERROR",
  "message": "Customer does not exist",
  "field": "customer"
}

The error field indicates the type of error, the message provides a human-readable explanation, and the field indicates which field caused the error. This makes it easier for clients to handle errors and display them to users.

How to Version Your API?

When you make breaking changes to your API, you should version it to avoid breaking existing clients. A common approach is to include the version in the URL, such as /v1/orders and /v2/orders. This allows you to support multiple versions of your API simultaneously and gives clients time to migrate to the new version. You can also use HTTP headers to specify the version, such as Accept: application/vnd.myapi.v2+json, but using the URL is simpler and more explicit.

How to Document Your API?

Documenting your API is essential for clients to understand how to use it. You can use tools like OpenAPI/Swagger to automatically generate documentation from your API definitions. Your documentation should include the URL, the HTTP method, the request body, the response body, and the status codes. It should also include examples of successful and failed requests. This makes it easier for clients to integrate with your API and reduces the number of support requests you receive.

How to Test Your API?

Testing your API is important to ensure that it behaves as expected. You can use unit tests to test individual domain services and repositories, and integration tests to test the API handlers and endpoints. Integration tests should cover successful requests, validation errors, and concurrency conflicts. They should also verify that the HTTP status codes and response bodies are correct. This gives you confidence that your API is reliable and consistent with the domain model.

REST API and DDD for Large-Scale Systems

For large-scale systems, you might need to break down your domain into bounded contexts. Each bounded context has its own domain model and its own API. For example, a bakery system might have a “Sales” bounded context for orders and a “Inventory” bounded context for products. The Sales API can create orders, and the Inventory API can update product quantities. To keep the system consistent, you might use events to notify the Inventory bounded context when an order is created, and the Sales bounded context when a product is out of stock. This approach helps you keep the domain model focused and makes it easier to scale the system.

How to Handle Cross-Boundary Operations?

When you need to perform an operation that spans multiple bounded contexts, such as creating an order and updating inventory simultaneously, you should use transactions or events to ensure consistency. For example, you might use a two-phase commit to ensure that both the order and the inventory are updated successfully. Alternatively, you might use events to notify the Inventory bounded context when an order is created, and let it handle the inventory update asynchronously. This approach gives you flexibility and makes it easier to scale the system.

How to Handle Events and Message Brokers?

When you use events to communicate between bounded contexts, you should use a message broker to deliver the events reliably. A message broker ensures that events are delivered to the correct bounded context, even if the receiving service is temporarily unavailable. You should also handle events idempotently, so that if an event is delivered multiple times, the bounded context can handle it without causing inconsistencies. This makes your system more resilient and easier to maintain.

How to Handle Eventual Consistency?

When you use events to communicate between bounded contexts, you should be aware that the system will eventually become consistent, but not immediately. This means that if you check the inventory after creating an order, it might not be updated yet. To handle this, you can use a query service that reads from both the order service and the inventory service and combines the results. This gives you a consistent view of the system and makes it easier to build user interfaces that reflect the current state.

How to Handle Circuit Breakers and Failures?

When you use a message broker to deliver events, you should use circuit breakers to handle failures. A circuit breaker monitors the health of the receiving service and opens when the service is unavailable. When the circuit breaker is open, the message broker stops sending events to the service and queues them locally. When the service recovers, the circuit breaker closes and the broker resumes sending events. This prevents the system from being overwhelmed by failed requests and makes it more resilient.

How to Handle Retry Policies and Timeouts?

When you use a message broker to deliver events, you should use retry policies to handle transient failures. A retry policy specifies how many times to retry a failed request and how long to wait between retries. You should also use timeouts to prevent the system from hanging. For example, you might set a timeout of 5 seconds for each request. If the request does not complete within 5 seconds, the retry policy will retry the request. This makes the system more reliable and easier to maintain.

How to Handle Backpressure and Throttling?

When you use a message broker to deliver events, you should handle backpressure and throttling. Backpressure occurs when the receiving service cannot keep up with the rate of incoming events. Throttling occurs when the receiving service is receiving too many events and needs to slow down the rate. You can handle backpressure and throttling by using rate limiting and queue depth monitoring. For example, you might limit the number of events per second to 100 and monitor the queue depth to ensure that it does not grow too large. This makes the system more stable and easier to maintain.

How to Handle Observability and Monitoring?