Introduction to APIs: A Beginners Guide to Understanding and Utilising APIs in Software Engineering
Getting started with APIs as a Software Engineer
What are API's?
Have you ever wondered how you can log into your favourite applications such as Facebook, Hashnode, dev.to, LinkedIn and so on? I know I got your attention and you have started thinking fast. Or have you imagined how easy it was to get into the WakaNow flight App and get the cheapest and most affordable fares from all around the World? Even football lovers are not left out as they can access scores in real time.
The answer to all these is that they communicate with other systems to get these data or to verify details, and the mode of communication is through an API.
In this article, the concept of API will be demystified and a very clear and apt understanding of what APIs are, their types and their mode of operation will be learned.
I. Introduction to APIs
A. What is an API?
An API which stands for Application Programme Interface is simply a tool by which systems or technologies can communicate with themselves by sharing information or data. It can further be explained as a layer by which systems can communicate with each other following a protocol or standard by which the sharing happens.
B. Why are APIs important?
APIs are important because it allows systems and technologies to interact with each other, share data, and functionality, and work together to create powerful, efficient systems. Furthermore, APIs give developers the super ability to bring applications together to perform a specific task. For example, a fashion blog and integrate Flutterwave API to allow customers to pay for designs or seminars, you can also use your Google account to login into any application linked to it.
APIs can be used to get data from third parties and exchange information, enabling us to do crazy stuff as Software Engineers.
C. How do APIs work?
Let us take this analogy into play, you want to study at a University. You have to follow a series of processes that would involve sitting for exams and with the result applying to your desired institution. You don’t have to go to the Admission Officer directly for an application, rather you simply visit their portal, input your details and upload credentials. While waiting for admission, a series of things happen at the backend you have no idea but will receive admission if the requirements are met.
The entire process is as follows, we want to communicate with the School admission Office and since we cannot access the Admission Office directly we use an API layer which in this scene is the School portal which you will refer to as an Endpoint. Each Endpoint has its protocol which is required and the expected result. In this example, the school portal is shielding you from every complicated thing going on in the admission office.
Imagine there was no admission portal, You will have to go to the University Admission Office to submit your details which will be time-consuming and not void of mistakes.
To connect two software applications via the internet, one program, known as the client, sends a request to the other application's API. The client requests a resource from the app's database or requests that an action be performed on the server.
After receiving and validating the client's request, the API takes the desired action and returns a response to the client. This answer comprises the request's status (finished or rejected) as well as any resources requested by the client.
Fig 1. The working of an API
D. Types of APIs
There are about four different types of APIs, which will be explained.
Public APIs: A public API or external API is a type of API that is made open and available for use to the general public. The owners of the API share their data and resources with 3rd parties which could include organisations, developers and the general public at large. The special purpose is to let anyone build with it, integrate it into applications or work on improving them.
Some examples of public APIs include; Bitquery, Adoptapet, covalenthq.
Private APIs:
A private API or Internal API is a type of API that is only available to the developers or individuals who built it. It can only be accessed when an invitation is sent by the owner(s) to the 3rd party.
Some examples of private APIs include;
Partner APIs
An application programming interface (API) given by a business or organisation to allow outside developers or partners to communicate and interact with their services, data, or platform is known as a partner API, also known as a third-party API or developer API. These APIs are intended to make it easier to integrate various systems, programmes, or services.
Organisations that wish to expand the usefulness of their goods or services and promote cooperation with outside developers or enterprises frequently provide partner APIs. With the help of these APIs, partners can create programmes, instruments, or services that make use of the data, functions, or technology of the business.
Some examples of partner APIs include;
Composite APIs
Composite APIs, also referred to as aggregation APIs or mashup APIs, are types of APIs that mix and aggregate information or functionality from several underlying APIs or services into a single interface. These APIs streamline the integration process and offer a consolidated view of several data sources by enabling developers to access and interact with different services through a single API.
When programmers need to continuously receive information or carry out several actions from many sources, composite APIs are helpful. A composite API enables developers to send a single request to access data or conduct actions across many services rather than sending separate queries to each API. The integration process is optimised, complexity is decreased, and efficiency is increased as a result.
Here's an example of a composite API that aggregates weather data from multiple weather service providers:
To aggregate weather data from these many suppliers and give developers access to a single weather data interface, a composite API may be created. This enables developers to get weather information from several sources with only one API request.
II. Types of APIs Architecture
A. Web APIs
Web APIs are the most commonly used because most of our daily activities revolve around the web. Web APIs are standards that allow things to be the same way on different browsers. It refers to both sides of the communication. Web APIs, commonly referred to as Application Programming Interfaces (APIs), are interfaces made available by web services or apps that enable online communication and interaction between them and other software programmes. Developers can programmatically access certain capabilities, services, or data from a web application or service thanks to web APIs.
1. RESTful APIs
RESTful APIs which stands for Representational State Transfer Application Programming Interface is a set of standards that allow computers to communicate with each other over the web following the design principles of the REST (or REpresentational State Transfer) architecture.
Part of a REST API Includes
Request -----→ Response
Operation - GET, POST, PATCH, UPDATE, DELETE
Endpoint - Url
Parameter/Body
Headers
Fig 2 A REST API diagram
The key principles of REST include:
Client-Server Architecture: REST separates the client and server components, enabling them to evolve independently. The client sends requests to the server, and the server processes those requests and sends back responses.
Statelessness: REST is stateless, which means that each request from the client to the server must contain all the necessary information to understand and process the request. The server does not store any client context between requests, simplifying scalability and allowing for better caching.
Uniform Interface: REST promotes a uniform set of interfaces and operations, typically using standard HTTP methods like GET, POST, PUT, and DELETE. Each resource in a RESTful system is uniquely identified by a URL (Uniform Resource Locator).
Resource-Based: REST treats everything as a resource, such as data entities, services, or collections. Each resource has a unique identifier and can be accessed and manipulated using standard HTTP methods.
Representation of Resources: Resources in REST are represented using a specific format, such as JSON (JavaScript Object Notation) or XML (eXtensible Markup Language). The server sends representations of resources back to the client, which can include data, metadata, or hypermedia links.
Stateless Interactions: Each request sent from the client to the server is self-contained and does not rely on any previous request or state on the server. This allows for better scalability, as the server does not need to maintain client session information.
Benefits of a REST API
Simple and standardized
Scalable and stateless
High-performance and cacheable
2. SOAP APIs
SOAP which stands for Simple Object Access Protocol is the web service that complies with the SOAP web services specification. It is a popular messaging protocol that uses XML as a format, well-defined schema and user-standard protocol. It is defined by the World Wide Web Consortium. SOAP protocols cover a broad number of internet communication protocols, notably HTTP, SMTP, and TCP/IP.
Fig 3 A SOAP API diagram
Benefits of using the SOAP API
Language, platform, and transport are independent.
Works well in distributed enterprise environments.
Provides significant pre-build extensibility in the form of the WS* standards.
Built-in error handling.
- RPC.
The remote procedural call (RPC) protocol is a means to send multiple parameters and receive results. It is a remote function call, it doesn’t exist on your local machine but is required to be deployed from where it is called. It is asynchronous in that you need to get a response to be marked as a success. It is a straightforward interaction between the Client and server. RPC APIs cause operational operations or procedures to be performed. RPC can employ two different languages, JSON and XML.
Fig 4 AN RPC protocol
GraphQL is a query language for APIs that allows clients to request specific data and shape the response according to their needs.
Some examples of GraphQL APIs
GitHub GraphQL API, Shopify GraphQL API, SpaceX GraphQL API, Yelp GraphQL API, Twitter GraphQL API (Twitter API v2).
Comparing API protocols
REST | SOAP | RPC | GraphQL |
Works with XML, JSON, HTTP and plain text | Works with XML by design | Requires Users to know Procedure names | Works with HTTP |
Works well with data | Works well with processes (actions) | Specific parameters and orders | |
Modest security | Advanced security | ||
Documentation can be supplemented by hypermedia | Most difficult for developers to use | Requires extensive documentation | |
Request method are GET, PUT, DELETE, PATCH, UPDATE. | Request method is POST | Request method is POST | Request method is POST |
III. Common API Terminology
A. Endpoints
An API Endpoint is one point or end of a communication channel. When an API interacts with another system, the touchpoints of this communication are called endpoints. In literal terms, the place where APIs send resources and where resources leave is called an Endpoint. In APIs, an endpoint is typically a uniform resource locator (URL) that provides the location of a resource on the server.
An example of an Endpoint is
Twitter API Endpoint Example
The Twitter API exposes data about tweets, direct messages, users, and more.
Let’s say you want to retrieve the content of a specific tweet. To do this, you can use the tweet lookup endpoint, which has the URL api.twitter.com/2/tweets{id} (where {id} is the unique identifier of the tweet).
B. Requests and Responses
An API request is a message sent from the Client to the server. An API request is a request made to an API to access or modify data or perform a specific action. An API response is the data or information that is returned in response to an API request.
For example, a User clicks on this hyperlink below;
<a href=’http://localhost:2400/categories/01/flavours ’>
Show all flavours available in the flavour category
</a>
The HTTP request message will be sent as:
GET /categories/01/flavours HTTP/1.1
Host: localhost:2400
User-Agent: Chrome/5.0 [compatible, Windows 10]
API request
1. Copy codeGET https://api.com/categories/flavours
API response
1. Copy codeHTTP/1.1 200 OK
2. Content-Type: application/json
3.
4. {
5. "id": 01,
6. "flavours": "Chocolate"
7. }
We can see from this request that the Endpoint is URL - /categories/01/flavours.
The Request method is GET, the HTTP Specification is 1.1, the domain is localhost, the port is 2400, Flavours is the resource, and the user-agent provides the browser and operating system.
C. HTTP Methods (GET, POST, PUT, DELETE)
APIs that utilize the HTTP protocol use HTTP request methods (also known as "HTTP verbs") for transmitting client requests to servers. The most commonly used HTTP request methods are GET, POST, PUT, and DELETE.
GET is used by a client to fetch data from a server,
PUT replaces existing data or creates data if it does not exist,
POST is used primarily to create new resources,
PATCH is used to partially update data from a resource, and
DELETE removes data or resources specified by the client on a server.
D. API Security - Authentication and Authorization
These two terms might sound similar but have two separate functions. Authentication has to do with the verification of users or identity while Authorization has to do with access a User has or permission granted for an action. They are core to API security, One popular method for authenticating and authorizing users is OAuth 2.0.
Different types of authorization
There are several methods for authorization. The following are various types of API authorization you might encounter:
API keys
E. API Keys and Tokens
API keys are strings of text that provide client App identification and client App authorization. In other words, they identify applications making calls to the server and whether the calling applications have granted access to the API server. It is used to track all activities and block any malicious behaviours.
API key authentication was created to address the shortcomings of shared login information, which is a major issue with HTTP basic authentication. It may be used for two purposes. The first step is to identify the client app, which is making a call to your backend API. The second step is client app authorization, which determines if the calling application has been granted permission to call the API.
API keys are gotten from API key providers managed on a web application.
Where to store your API keys
Never embed your keys in your code or in files because they may find their way to the public when you push to GitHub, rather store your API keys in an environment variable.
An example of an API key could look as follows.
key: a9nIbdnaoks97028Jlf.ains9NIKQMEO
An access token is a security credential that is used to authenticate and authorize access to an API (Application Programming Interface). Tokens are simply unique credentials for the bearer of the token who is allowed to access an API.
Here's an example of a JSON Web Token (JWT):
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
This is a JWT composed of three parts separated by dots: the header, the payload, and the signature. The header typically contains information about the token's algorithm used for signing, for example:
{
"alg": "HS256",
"typ": "JWT"
}
The payload contains the claims or statements about the entity (user, client, etc.) and can include information like the subject, issuer, expiration time, and custom data. For example:
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
The signature is created by taking the encoded header, payload, and a secret key, and applying a cryptographic algorithm, such as HMAC-SHA256. The signature ensures the integrity and authenticity of the token.
When using this JWT, the client includes it in the authorization header of API requests like this:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
The API server can then verify the token's authenticity, check its expiration, and use the information contained in the payload for authorization and other purposes.
Please note that the example token provided here is for illustrative purposes only and should not be used in a production environment.
Tokens and keys are both used for authentication and authorisation, however, they differ in the following ways:
API keys are typically used for client or application identification and authentication when visiting an API. They frequently take the form of lengthy, randomly generated strings that serve as credentials. Tokens, on the other hand, are given to authorised clients or users following a successful authentication procedure and serve as proof of authentication.
Lifespan: Unless deliberately revoked or rotated by the API provider, API keys generally have a lengthy lifespan. Tokens, on the other hand, frequently have a short lifespan and an expiration date. Depending on the authentication technique, the client must either re-authenticate or use a refresh token to receive a new token once the old one expires.
Security: Tokens generally offer better security features compared to API keys. Tokens can be designed to have limited scopes or permissions, allowing fine-grained access control. They can also be encrypted, signed, or contain additional claims that provide integrity and authenticity. This allows for more secure authentication and better protection of sensitive data.
Real-world Examples and Use Cases
A. Weather API
Weather APIs, or Application Programming Interfaces, are services that provide real-time access to weather data and forecasts.
Examples include
. WeatherAPI.com, Forecast, Meteostat.
B. Social Media API
Social network APIs allow these platforms to integrate with other software providers and apps.
Examples include
C. Payment Gateway API
The technological interface that allows software developers to incorporate payment gateway services into their apps or websites is referred to as a payment gateway API.
Examples include
Stripe API. Stripe is a highly-acclaimed service that allows vendors to accept payments online, Noodlio Pay, Square API, PayPal, Adyen, Paybook, KeyPay, BIPS Invoice (By Coinify).
D. Mapping and Geolocation API
The Geolocation API does not retain any information but rather allows you to gather existing data from the device being queried. It may gather position data from different sources, including IP address, GPS, WiFi, Bluetooth, RFID, GSM/CDMA ID, and human input.
Examples include Geolocation API, Mapbox API, OpenStreetMap API, MapQuest API, HERE API.
IV. Conclusion and Take Home
Throughout this article, it has been established what APIs are, how it works, real-life examples, APISecurity, HTTP methods and the importance of APIs. It has been deduced that API enables Software Engineers to integrate applications into what is being built and even improve on it. In the course of my research and writing, I discovered that a huge issue is API security. If there is an API is hacked it will affect all applications connecting to it so I would further my research on API Security.
Finally, I will be releasing another article in relation to this as it will be on exploring APIs, working with APIs in codes, API best practices, API design and development.
A. Some keywords include
API - Application User Interface
RPC - Remote Procedural Call
HTTP - Hypertext Transfer Protocol
B. Next steps for further learning
Finally, I will be releasing another article about this as it will be on exploring APIs, working with APIs in codes, API best practices, API design and development.