Designing, Building, and Specifying APIs
The technical author has many options when designing and building APIs. While building a service with modern technologies and frameworks can be incredibly fast, creating an enduring approach that stands the test of time requires careful thought and deliberation. In this article, we will examine REST and RPC models that are frequently used in API implementations.
One key understanding in this journey will be the role of standards in steering design decisions and evading potential compatibility issues. We’ll also examine OpenAPI Specifications, understanding their practical applications for technical teams and the crucial versioning aspect.
RPC-based interactions are generally specified using a schema; to compare and contrast with a REST approach, we will explore gRPC. With REST and gRPC in mind, we will look at the different factors to consider in model exchanges. We will also consider whether providing a REST and RPC API in the same service is practical.
Representation State Transfer (REST) is a set of architectural conditions commonly applied using HTTP as the underlying transport protocol. From a practical perspective, to be considered RESTful, your API must ensure that:
- A producer-to-consumer interaction is modeled where the producer models resources the consumer can interact with.
- Requests from producer to consumer are stateless, meaning the producer doesn’t cache details of a previous request. To build up a chain of requests on a given resource, the consumer must send any required information to the producer for processing.
- Requests are cachable, meaning the producer can provide hints to the consumer where appropriate. In HTTP, this is often provided in the information contained in the header.
- A uniform interface is conveyed to the consumer. You will explore the use of verbs, resources, and other patterns shortly.
- It is a layered system, abstracting away the complexity of systems sitting behind the REST interface. For example, consumers should not know or care if they interact with a database or other services.
Introduction to REST and HTTP by Example
Let’s see an example of REST over HTTP. The following exchange is a GET request, representing the method or verb. A verb such as GET describes the action to take on a particular resource; in this example, we consider the attendees resource. An Accept header is passed to define the type of content the consumer would like to retrieve. REST defines the notion of a representation in the body and allows for representation metadata to be defined in the headers.
In the example below, we represent a request above the — separator and a response below:
GET http://mastering-api.com/attendees
Accept: application/json
—
200 OK
Content-Type: application/json
{
“displayName”: “Jim”,
“id”: 1
}