Wrapping up– REST APIs

With a method (verb), the client (and the endpoint) can express the intent to create, update, read, or delete an entity. With a status code, the endpoint can tell the client the state of the operation. Adding HTTP headers, clients, and servers can add more metadata to the request or response. Finally, by adding versioning, the REST API can evolve without breaking existing clients while giving them options to consume specific versions.With what we just covered, you should have more than what’s needed to follow along with the examples in this book and build a few REST APIs along the way. Next, we explore how those HTTP pieces create API contracts.

Data Transfer Object (DTO)

The Data Transfer Object (DTO) design pattern is a robust approach to managing and transferring data in a service-oriented architecture like REST APIs. The DTO pattern is about organizing the data to deliver it to API clients optimally. DTOs are an integral part of the API contract, that we explore next.

Goal

A DTO’s objective is to control an endpoint’s inputs and outputs by loosely coupling the exposed API surface from the application’s inner workings. DTOs empower us to craft our web services the way we want the consumers to interact with them. So, no matter the underlying system, we can use DTOs to design endpoints that are easier to consume, maintain, and evolve.

Design

Each DTO represents an entity with all the necessary properties. That entity is either an input or an output and allows crafting the interaction between the clients and the API.DTOs serve to loosely couple our domain from the data exposed over the API by adding a level of abstraction. This allows us to change the underlying domain model without affecting the data exposed to the API consumers and vice versa.Another way to use a DTO is by packaging related pieces of information together, allowing a client to make a single call to fetch all necessary data, thereby eliminating the need for multiple requests.Based on REST and HTTP, the flow of a request goes like the following: an HTTP request comes in, some code is executed (domain logic), and an HTTP response goes back to the client. The following diagram represents this flow:

 Figure 4.1: An HTTP request getting in and out of a REST API endpoint.Figure 4.1: An HTTP request getting in and out of a REST API endpoint. 

Now, if we take that flow and change HTTP with DTO, we can see that a DTO can be part of the data contract as an input or an output:

 Figure 4.2: An input DTO hitting some domain logic, then the endpoint returning an output DTOFigure 4.2: An input DTO hitting some domain logic, then the endpoint returning an output DTO 

How can the HTTP request become an object? Most of the time:

Let’s look at a few examples.

You may also like