The ABCs of building an API

The ABCs of building an API

A deep dive into different API architectures, features and use cases.

API is one of the most used word in the tech space and if you’re just starting off a career in tech, then you need to fully grasp the concept. Even if you’ve been in the industry, I believe a refresher course is in order. We all refresh our browsers.. don’t we?? 😂

Every Software Engineer at one point or the other must have either accessed, documented, created or consumed an API. API stands for Application Programming Interface. It is a set of definitions, rules or protocols that allow applications to talk to each other. As a developer, you create the API, host it on a server and other authorised apps or services can talk to it.

In this article, We will be looking at what the term API really means with examples and the different API architectures. tenor.gif

Ever wondered how your favourite weather app get daily weather forecast across to you? or how your Uber app tracks your pickup location? Even more is how different cash/finance applications are able to verify account numbers issued by different banks?. How does your favourite e-commerce platform provide payment or checkout experience to customers??.

The answer is simple. They leverage other services to get the needed data and this is done through an API.

For example, if you visit a restaurant, you can’t just walk straight into the kitchen and prepare yourself a meal. You follow certain procedures. You first meet the waiter, place your order from available menu choices and probably sit down and wait. The waiter takes your order to the kitchen and you have little or no idea as to what is happening behind the scene in the kitchen.

An API works in a similar way. The API(waiter) receives your request/order, the request is sent to the kitchen and when the food is ready, you are served the requested resource(food). Note that, just as the same waiter serving you can attend to other customers, An API is designed to handle multiple requests.

Group 4.png

An API is typically an interface that defines the communication between two or more applications. As an intermediary, it delivers a client’s request to the server and then returns a response back to the client. Remember, the goal has always been to get food from the restaurant. However, you don’t have direct access to the kitchen except through the API layer - the waiter. For the most part, an API defines acceptable calls or requests that can be made, how to make them, the data formats to be used and the conventions to follow.

Why Do we Need An API

  • APIs abstract complicated logics away from consumers, allowing them to continuously interact with the interface with little or no knowledge of the background implementation or the data source.
  • API helps us to create reusable services.
  • APIs provide a way for organisations to share certain information to customers while maintaining security and control.

Architectural styles

In order to build a great software that scales and meet other requirements, certain decisions must be made. One of such decisions is the architectural style to follow. This design decision is foundational and have a great deal of effect on the overall outcome. Below are some of the widely used architectural styles.

REST

If you've heard of the term API before, chances are that you must have heard of RESTful services. REST is an acronym for Representational State Transfer. Oops!!,😜 I know what you are thinking.. another super story… Hold on, let’s try an analogy, at least in English.

Let’s say you want to buy a new phone from amazon, you’ll probably visit amazon website, search for the phone model and boom! you’ll see details of the product for you to checkout. However, behind the scene, a request is sent to fetch certain information about the product. Such request may be to check if the phone is still in stock, the current selling price, the warranty and other descriptions of the product from the server. A REST API works in a similar way. You send a request to an endpoint with some payload, and a list of results returned back from the service.

REST is a very popular architectural style that developers follow when creating and consuming APIs. APIs that follow the REST architectural style are called RESTful APIs. In a RESTful service, requests made to a resource's URI will elicit a response returned in a specific format (HTML, XML, JSON, etc).The response can also provide hypertext links to other related resources.

A RESTful API is defined by the following constraints:

  • Client-Server architecture: This constraint creates a separation of concern in the system. With the client-server approach, the system making the request is different from the one processing the request and returning response. This improves portability as each part of the system can grow and scale independently.
  • Statelessness: For the client-server communication to be stateless, each request or API call must contain all the needed information to process the request and return a response. In other words, the extrinsic state(application state) is stored on each client and can only be passed from the client to the server when needed.
  • Cacheability: Cache constraint requires that responses from a RESTful service be explicitly defined as either cacheable or non-cacheable to prevent clients from serving stale data for equivalent requests. Well-managed caching improves scalability, internal server usage and performance as clients can reuse cacheable responses. So if a response to a request is flagged as cacheable, clients will know to reuse such response for future equivalent requests instead of making new API calls.
  • Layered System: This constraint defines a layered structure with each layer having a specific functionality and interconnected with other component part of the system. It defines a hierarchical structure where the introduction of additional layers(proxy, load balancer, security layer etc) does not affect the internal workings of the system. A layered system helps create a more scalable and modular application.
  • Uniform Interface between components: This constraint is key to the design of any RESTful service. It implements the Generality principle and encourages a uniform way of interacting with a given server and referencing resources.

Why RESTful APIs

  • They are simple and standardised approach to communication.
  • They are scalable and stateless.
  • They are fairly high-performant due to support of caching.

In a RESTful API, HTTP methods are used to identify the action. Some of the HTTP methods are – GET, PUT, POST, DELETE, UPDATE, PATCH.

HTTP MethodsActionExample
GETObtain information about a resourceexample.com/api/recipes/3
POSTCreate a new resourceexample.com/api/recipes
PUTUpdate a resourceexample.com/api/recipes/3
DELETEDelete a resourceexample.com/api/recipes/3

SOAP

SOAP stands for Simple Object Access Protocol. It is an XML-based messaging protocol for exchanging structured data between applications. SOAP makes it easier for apps running in different environments or written in different languages to communicate and share information. Unlike REST architecture, SOAP follows preset standards such as messaging structure - A set of encoding rules and a convention for providing procedure requests and responses.

Key Features of SOAP

  • XML Data Exchange Format: SOAP uses XML(Extensible Markup Language) - A markup language that defines a set of rules for encoding messages in a format that is both human-readable and machine-readable.
  • Messaging Structure: Standard SOAP API requests and responses are structured as an enveloped message consisting of SOAP Envelop, SOAP Header and SOAP Body, with each having a specific function.
  • Compliance to ACIDity principle: ACID(Atomicity, Consistency, Isolation, Durability) - A set of guiding principles that ensure transactions can be processed reliably. This is one of the reasons why SOAP is used when exchanging sensitive enterprise-grade information across applications.
  • Platform Independence and extensibility.

Building Block of a SOAP Message.

A SOAP message is an XML document consisting of the information being exchanged between two or more SOAP nodes. It is made up of:

  • An Envelop: The envelop acts as an identifier that encapsulates the data in a SOAP message which is exchanged between services. It is a required element that indicates the beginning and end of a SOAP message.
  • Header: A SOAP header is an extension mechanism that provides a way to pass control information in SOAP messages. Such "control" information includes, passing directives or contextual information related to the processing of the message. The header element can also be used to pass information such as authentication information or the definition of complex data types. This allows a SOAP message to be extended in an application-specific manner.
  • Body: The SOAP body is a required element within the SOAP env:Envelope. It contains the main end-to-end information conveyed in a SOAP message. It also contains the definition of the web methods along with any required parameter. The interpretation and processing of SOAP body is defined by header blocks.
  • SOAP fault: The Fault element contains errors that are triggered between the request and response.

GraphQL

In its simplest form, GraphQL is a data layer query language that provides declarative data fetching. It allows clients to define the exact structure of the data required, and the same structure of data is returned from the server, no more and no less.

By using a declarative data fetching mechanism, GraphQL prevents excessively redundant large amount of data from being returned.

GraphQL uses a Schema Definition Language (SDL) to define the schema of an API. This schema is one of the most important items when working with a GraphQL API. Simply put, a schema is a collection of GraphQL types. It specifies the capabilities of the API and defines how clients can request data. A schema is defined with fields mapped to types and It is often seen as a data access contract between the server and client.

In GraphQL, data interaction is done using Queries,Mutations and subscriptions. Instead of multiple endpoints that return fixed data structures, a GraphQL server only exposes a single endpoint and responds with precisely the data a client asked for. This solves the problem of over-fetching and under-fetching.

Under-fetching refers to a situation where a specific endpoint does not provide enough of the required information. This often leads to making (n+1) requests in order to get all the needed information. Over-fetching on the other hand, means fetching more than required data.

GraphQL is mostly used by services that priorities giving clients exactly the data they request, and no more or less. It is designed to be fast and flexible, although this flexibility can add extra complexity that may not be worthwhile for simple APIs. With GraphQL, developers can construct queries that pull data from multiple sources in a simple API call.

For the most part, GraphQL returns status code(200) for any valid response(both data and error) and errors are handled as part of the response body under a special errors object. This is in contrast to REST-ish architecture that returns different status codes for different response types.

Conclusion

In this article, we have highlighted some of the architectural styles for designing an API. APIs have become ubiquitous components of software infrastructures. Different API architectures have different use cases and a careful understanding of the service you are building will better inform your choice of an API architecture.