API Paradigms

Priyanka Masne
6 min readJun 28, 2021

Building blocks for interoperability of major business platforms

Application Programming Interface

What? — An API is the interface that a software program presents to other programs, to humans and in case of web APIs, to the world via the internet.

Why? — APIs have emerged out of a need to exchange information with providers of data who are equipped to solve a specific problem, so folks at other companies don’t have to spend time solving those problems themselves.

For whom? — It depends on the use-case. It is important that we specify our API to our customers and validate it long before we start to implement it. The cost of switching from one API design to another is extremely high.

API Paradigm? — It defines the interface exposing backend data of a service to other applications. There are many paradigms — REST, RPC, GraphQL, WebHooks, WebSockets etc.

Request-Response APIs

Request-Response APIs typically expose an interface through an HTTP-based web server. These APIs define a set of endpoints. Clients make HTTP requests for data to those endpoints and the server returns responses typically as JSON or XML.

Request-Response APIs are typically exposed by 3 common paradigms — REST, RPC and GraphQL.

Hypertext Transfer Protocol

HTTP is an application layer protocol designed to transfer data between networked devices. A typical flow over HTTP involves a client machine making a request to a server, which then sends a response back.

A typical HTTP request contains —

  1. HTTP version type
  2. a URL
  3. an HTTP method — GET, POST, PUT, PATCH, DELETE
  4. HTTP request headers
  5. HTTP body (optional)

Just like Web pages, APIs have URLs and addresses too. Defining these URLs/Addresses comes under paradigms — REST, RPC, GraphQL etc.

HTTP Request Headers contain text information stores in key-value pairs. These headers communicate core information such as browser the client is using, data that is being requested

:authority: www.google.com
:method: GET
:path: /complete/search?q=hello%20world
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-GB,en-US;q=0.9,en;q=0.8
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36

A typical HTTP response contains —

  1. an HTTP status code
  2. HTTP response headers
  3. HTTP body (optional)

HTTP Status code are 3-digit codes most often used to indicate whether an HTTP request has been successful —

  1. 1xx — Informational
  2. 2xx — Success
  3. 3xx — Redirection
  4. 4xx — Client Error
  5. 5xx — Server Error

The “xx” refers to different numbers between 00 and 99.

Example HTTP Response Header

cache-control: private, max-age=0
content-encoding: br
content-type: text/html; charset=UTF-8
date: Sat, 26 Jun 2021 19:02:03 GMT
status: 200
strict-transport-security: max-age=31536000

Representational State Transfer

REST is all about resources. A resource is an entity that can be identified, named or addressed. REST APIs expose data as resources and use standard HTTP methods to represent CRUD transactions against those resources.

REST APIs general rules —

  1. Resources are part of URLs — /users
  2. For each resource, 2 URLs are generally implemented — one for the collection like /users, and one for specific element like /users/U123
  3. Nouns are used instead of verbs for resources — Not getUserInfo/U123 but /users/U123
  4. HTTP methods like GET, POST, PUT, DELETE inform the server about the action to be performed. Different HTTP methods invoked on the same URL provide different functionality
  5. REST APIs might return JSON or XML responses

Example:

GET /zipcode/456010
HOST weatherapp.com
Authorization: Bearer w4j6hyb78onjurt4
-----------------------------------------POST /zipcode/456010
HOST weatherapp.com
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer w4j6hyb78onjurt4
temperature=27C&isRainy=true

REST APIs might sometimes need to represent non-CRUD operations —

1. Render an action as part of a field of a resource

PATCH /repos/pmasne/Hacks
HOST api.github.com
Content-Tyep: application/json
Authorization: token OAUTH-TOKEN
{
"archived": true
}

2. Treat an action like a subresource. Github uses below pattern for locking and unlocking an issue

PUT /repos/:owner/:repo/issues/:number/lock

3. Some operations like Search are difficult to fit in the REST paradigm. A typical practice is to use the action verb

GET /search/code?q=:query:

Remote Procedural Call

Where REST is about resources, RPC is about actions. Clients typically pass the method name and arguments to the server and receive back JSON or XML.

RPC style works great for APIs that expose a variety of actions that might have more nuances and complications than can be encapsulated with CRUD operations on resources. Slack’s conversations API allows several actions, like archive, join, kick, rename etc. Not all these actions would fit into REST pattern nicely.

Example:

POST /api/conversations.archive
HOST slack.com
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer ds234hjb45jb4353j45l
channel=C01234

GraphQL

GraphQL is a query language for APIs that was developed internally by Facebook and then released publicly. It allows clients to define the structure of the data required and the server returns exactly that structure.

GraphQL query - 
{
user(login: "pmasne") {
id
name
company
createdAt
}
}
GraphQL query response -
{
"data": {
"user": {
"id": "pmasne",
"name": "Priyanka Masne",
"company": "Facebook",
"createdAt": "2021-08-01T21:00:06Z"
}
}
}

Unlike REST and RPC APIs, GraphQL APIs need only a single URL endpoint. Similarly, we don’t need different HTTP verbs to describe the operation. Instead, we can indicate in the JSON body whether we are performing a query or mutation.

Advantages (GraphQL vs REST/RPC) —

  1. Saves multiple round trips
    GraphQL enables clients to nest queries and fetch data across resources in a single request. Without GraphQL, this might require multiple HTTP calls to server. This means GraphQL can be quick, even on slow network connections.
  2. Avoids versioning
    You can add new fields and types to a graphQL API without affecting existing queries. Similarly deprecating existing fields is easier.
  3. Smaller payload size
    REST and RPC often end up responding with data that clients might not ever use. With GraphQL, because clients can exactly specify what they need, the payload sizes can be smaller.
  4. Introspection
    Although, REST APIs can be explored on solutions like Swagger or Postman, graphQL is natively discoverable. It comes with GraphiQL, an in-browser IDE.

Disadvantage — GraphQL adds complexity for the API provider. The server needs to do additional processing to parse complex queries and verify parameters. Depending on the complexity of the incoming requests, the performance and impact to infrastructure can be highly variable.

Event-Driven APIs

Sometimes the applications need to push the data to clients to keep it up-to-date as the polling can at a high frequency would lead to a huge waste of resources.

Three poplar paradigms to share data in real time — WebHooks, WebSockets and HTTP Streaming.

WebHooks

WebHook is just a URL hat accepts an HTTP POST (or GET, PUT, DELETE). An API provider implementing WebHook will simply POST a message to a configured URL when something happens.

From an app developer’s POV, it’s typically easy to implement WebHooks because it simply required creating a new HTTP endpoint to receive events.

Complexities —

  1. Failures and Retries
    To ensure WebHooks are delivered successfully, it’s important to build retry mechanisms on error.
  2. Security
    Although there are standard ways of making REST APIs secure, security for WebHooks is still evolving.
  3. Firewalls
    Applications running behind firewalls can access APIs over HTTP but they cannot receive inbound traffic. For such applications, utilising WebHooks is often not possible.
  4. Noise
    Typically, each WebHook call represents one single event. When there are thousands of events happening, WebHook can be noisy since events can be sent in bulk.

WebSockets

WebSocket is a protocol used to establish a two-way communication channel over a single TCP connection. It doesn’t use HTTP. It is supported by major browsers and often used by real-time applications.

Advantages —

  1. WebSockets are designed to work over port 80 or 443, enabling them to work well with firewalls that might block other ports.
  2. WebSockets are great for fast, live streaming data and long-lied connections.

Disadvantages —

  1. Clients need to reinitiate connection in case the connection is broken. In low network bandwidth regions, this can be spotty.
  2. Developer needs to ensure scalability. If the app is installed on 1M devices, the developer would be responsible for maintaining 1M connections between backend servers and the app’s server.

HTTP Streaming

With HTTP request-response APIs, clients send an HTTP request and the server returns an HTTP response of a finite length. Now it’s possible to make the length of this response indefinite. With HTTP streaming, the server can continue to push new data in a single long-lived connection opened by a client.

To transmit data over a persistent connection from server to client, there are 2 options —

  1. server can set Transfer-Encoding header to chunked. This indicates to clients that data will be arriving in chunks of newline-delimited strings.
  2. Data can be streamed via server-sent events (SSE). This is great for clients consuming these events in a browser because they can use the standardized EventSource API.

Disadvantages —

  1. Bi-directional communication is difficult.
  2. Clients and proxies have buffer limits. They might not start rendering data to the application until a threshold is met.

--

--