DEV Community

Cover image for What is really an API? Examples, Code + History
Samuel Kufre Willie
Samuel Kufre Willie

Posted on

What is really an API? Examples, Code + History

Introduction

What is an API?

This is a common question that every new developer will often ask when introduced to the concept.

The next question after that is usually, what is the need for an API?

I will try to answer these questions here.

There is a lot of documentation about what an API is on the internet. However, the issue with most of these documents is that they are not tuned to meet beginners' demands.

For example, if you search “What is an API” in your browser, a common search result you will see is;

API stands for Application Programming Interface

While this is the correct meaning of an API, it is, however, still too bogus for beginners to grasp.

In this article, my main objective is to develop a reference resource that will describe an API in such a way that regardless of your level of programming, you will quickly understand the concept of API and its use cases.

To achieve this goal, I will use real-life examples for demonstration and also include some very small code samples in Python.

You will also learn what Microservice and Monolithic Applications are.

At the end of this article, you would be able to;

a. Understand what an API is and it's benefits.
b. Define, interact and build your API, etc.

This resource is also suitable for people with non-coding backgrounds and can also be used as a classroom resource for explaining what an API is.

Prerequisites

If you wish to follow along with some coding samples, you will need the following:

  • Mac/Window OS
  • Bash terminal / Window Command Prompt
  • Python installation

Aside from that, you can still use this resource without these requirements.

So, What is an API?

Let's start this with a beautiful illustration.

Nigeria has some very large and busy marketplaces in the world. Some of these markets contain thousands of people at a time and hundreds of shops lining up each street.

Now imagine yourself in one of these bustling market streets.

Vendors line the streets, each specializing in their craft - the baker with warm pastries, trolleys navigating through tiny gaps, and the tailor with exquisite fabrics.

You, however, are tasked with creating a magnificent outfit for a bride.

If you are a new person in this market, two things are likely to happen;

  1. You will miss your way inside the market
  2. You will buy stuff at an overpriced rate

Instead of running from one shop to another, haggling for each piece, you choose to approach a well-respected merchant.

Let's call him "Mr. API."

Now Mr. API has something very important, he possesses a detailed catalog of every vendor's wares, their specifications and rate- the type of bread the baker offers, the size and style of boots the cobbler crafts, and the fabrics and patterns the tailor utilizes.

Everything.

You simply tell Mr. API your requirements - a soft, white blouse, 5-inch heels, and a flowing white cape.

Mr. API, acting as a smooth negotiator, seamlessly communicates your needs to each vendor, retrieves the perfect items from their respective "stock," and delivers them to you, ready to be assembled into your dream outfit.

Just like Mr. API in the market, an actual API acts as a middleman, facilitating communication and exchange between different software applications.

It retrieves specific data or functionality from one program (the vendor) and delivers it to another (you), enabling them to work together seamlessly to achieve a desired outcome.

This hidden exchange of information powers the countless applications, tools, and services we use daily, making our digital lives smoother and more interconnected.

Now, let's bring this back home to you as a developer

Assuming you are tasked with building a weather application, while you can design the application front end and write the backend code easily, there is a piece of requirement you will not have natively.

That is the weather data.

To make your application useful, you will need accurate weather information from reliable sources.

Luckily for you, just like the illustration we shared above, some platforms give out accurate and timely weather information through their APIs.

All you have to do is follow their protocols and request this API to deliver any weather information you need to build your applications.

We will look at how to make these kinds of requests in the subsequent section.

As a developer, you will work with APIs in two ways.

  1. As a Creator: Building APIs and adding features for other developers or platforms to use
  2. As a consumer: Retrieve data from other APIs to power, improve, or develop your platform.

As you go further in this article, you will begin to appreciate why API is not only an essential component of software development but also why it is a very powerful tool.

But first, let's look at the Benefits API brings.

Benefits of APIs in Everyday Life

API has a lot of benefits. As we see from our illustration above, it can help developers build applications faster by leveraging data generated from a different platform.

But that is not all, in this section, we will see other benefits of API in real life.

Let's start with the first one.

a. Separation of services.

Considering the image below, a simple software application depending on the complexity can consist of different types of services coming together to make it perform its duties

a simple software application

Assuming our sample application is an event listing platform where users are required to create an account, make payments, and list their events on the platform,

As a developer, you might decide to build all of these components like an authentication system that verifies users, a payment gateway to accept payment, a notification system to send users notifications, etc.

But that is not the only option. Other well-tested and trusted platforms can help you solve this problem easily and build your application faster.

For example, you can rely on the powerful OAuth by Okta to handle your Auth services, Flutterwave payment gateway to accept payment, and Google Firebase Messaging to manage notifications.

This is easily achieved through API gateways designed and offered by these companies.

b. Fast Development process
Following up on our example above, because different parts of our application services are offered by 3rd party platforms, our development timeframe will now be relatively shorter since we do not have to worry about building these ourselves.

And even more, more developers can join the development team and take charge of different parts of the applications.

c. API promotes ease of maintenance and business expansion

WebAPI components
Image credit: zellwk.com

At a high level, a typical application consists of three (3) parts, the client-side(Front-End), the server-side(BackEnd), and the Database.

In the early days of web development, when building applications, all these parts were combined into a single codebase.

The type of applications built this way is called _Monolithic Applications. _

However, there are a few common problems with monolithic apps.

While they are easier to build, they can become difficult to maintain as the codebase continues to grow.

Also, because it is a single codebase, it is difficult for other developers to join in and contribute which of course defeats innovation.

One of the solutions to these problems is an application architecture called Microservices Architecture.

In microservices applications, each component of the app is built separately.

For example, the client side can be built by a different team of developers and hosted on a different domain like www.example.com while the server side can also be built by a different team of developers and hosted on a domain like api.example.com.

The next question is, how does this component communicate and share data in such a way that it won’t affect a user?

That is where API comes in.

Because API offers communication protocols, developers working on each of the app components can send and receive data seamlessly using the API protocols.

These allow for:

  • More application services can be added or removed without affecting the overall application.
  • More developers to join the team and build independently
  • Bugs or even bigger problems to be isolated and tackled separately without effectively the entire codebase.

You will see more of this when we build a simple API in subsequent sections.

History of APIs

API has come a long way.

The concept itself was developed to allow computer services to communicate effectively with other services. However, API became popular because of the need to share resources.

In the early 2000s, companies like Salesforce, eBay, and Amazon wanted to allow other people, especially developers, to incorporate their services into their websites and API was one way to achieve that.

For example, Amazon wanted other people to be able to list Amazon products on their website.

Today, things like being able to embed Twitter posts on blogs, create games with Facebook user data, etc. are all possible through the API endpoints exposed by this platform.

If you want to read more on API history, postman has an interesting article on it here

Different Types of API: Understanding Public, Private, Web and Non-Web APIs

APIs can be grouped or classified into different types depending on their access level, the platform it is built on, and the protocols they follow.

In this section, we are going to look at Public vs Private APIs, Web vs Non-Web APIs, and Restful vs Soap APIs.

PUBLIC API vs PRIVATE API

Let's go back to our story with Mr.API. The reason why you could use Mr. API's services in the Nigerian market is simply because he is open for everyone to use.

Imagine if Mr. API's catalog of merchants and their goods was only developed for himself and his family alone, then nobody else would be able to enjoy his services even at a fee.

That is the same logic with Public or Private APIs.

Some APIs are designed to be used in the internal environment. That is only within the business environment developing it. These types of APIs are called private APIs.

A good example is an API that is developed by a team building a web and Mobile application of an e-commerce platform.

However, some APIs are open for use by everyone. These are known as public APIs.
Despite being public, these types of APIs still have different protocols to follow, use case limits of usage, etc.

An example of a Public API is the weather data API offered by OpenWeatherMap.

Partners API

Partners APIs are public APIs designed for only specific organizations. They are designed to share business logic with businesses that are in the partnership.

For example, Facebook has specific API endpoints that are designed to share certain services with its WhatsApp business.

Webs APIs vs Non-web APIs

The main difference between web and non-web APIs is in their characteristics and functionalities.

While web APIs rely on the internet and HTTP protocol to share data, non-web APIs do not necessarily do that.

For example, your phone camera, which is an example of a non-web API, does not require the internet to store pictures in your phone memory.

However, downloading images from unsplash.com requires an internet connection.

I have summarized the key difference between these two APIs in the type below.

Summary of web vs non web api features

Restful APIs vs Soap APIs

As API use cases continue to grow, there is a need to maintain standard and common uniformity so that providers and consumers of API can know what to expect when creating or consuming APIs.

Restful and SOAP APIs are two of the common standards that API developers can follow when designing the API. Among these two, RESTFUL API is the most popular and widely used when designing web APIs.

RESTFUL API

REST is a short form of Representational State Transfer.

This API design standard came out of the Ph.D. thesis of Dr. Roy Fieldings in 2000 and defined a set of constraints that an API should follow to be considered RESTFUL.

Features of REST API,

  • Restful API share resources using the HTTP communication protocol
  • The Restful API service has a client side, a serve side and resources
  • Unlike SOAP, RESTFUL APIs support caching.

  • Every communication is stateless, meaning that no data is stored
    between requests.
    That is each new request is different,
    separate and unconnected to the preceding or succeeding request,
    etc.
    The popularity of the RESTFUL API design pattern is partly because it is faster, simple, and lightweight than other API design patterns.

SOAP API

SOAP is a short form for Simple Object Access Protocol.
It is another popular API-designed pattern built around XML. XML is an acronym for Extensible Markup Language.

While RESTFUL API requires HTTP as a protocol to establish communication and ensure resource sharing, SOAP can leverage other protocols such as simple mail transport protocol (SMTP), transmission control protocol (TCP), etc.

The biggest flex with the SOAP API design pattern is that it ensures a developer creates a more secure API since data is transported in XML format.

Ultimately, while REST APIs are more popular, your choice of an API design pattern depends on your requirements and considerations.

Common API terminologies

Now that we have covered the basics of APIs, what they are, and what they do, let's look at the common terminologies you will come across when developing or consuming an API

a. Protocol
In simple terms, a protocol is a language that an API understands and also uses to receive and share resources with consumers.
For RestAPIs, the common protocol is the HTTP protocol which stands for HyperText Transfer Protocol while SOAP APIs also support HTTP, SMTP, and TCP.

A protocol also covers the format of data exchange between a server and a client. It specifies the message expectation of the API and how it behaves when there is an error.

b. HTTP
As I explained above, HTTP is one of the communication protocols an API can employ. HTTP is popular for the methods it uses when sharing data.

Some common examples of HTTP methods are;

  • GET: The method used to request data from an API
  • POST: The method used to create a record through an API
  • UPDATE: A method used to make partial changes to a record through an API
  • PUT: A method used to make full changes to a record through an API
  • DELETE: The record used to remove a record through an API

v.CRUD
CRUD is an acronym for Create (POST), Read (GET), Update (UPDATE/PUT), and Delete. It is used to explain an API or apps that permits these four operations through it.

d. API Request and Response
Request and Response are the fundamental elements of API communication.

To better explain this, let me take you back to Mr. API in the Nigerian market.

When you want something, you requested it through Mr. API and he returns with a message which is a response.

So request and response are the two ends of an API provider interaction with a consumer.

Like in real life, the response to a request is not always as we expected.

e. Status Code
Status codes are HTTP codes that are used to define the result of our API request.

Sometimes, an API might not be able to handle our request, or the resources we are looking for might have changed.

In worst cases, we might not even have permission to use that API.
The status code carries information about this.

For example, HTTP status code 200 means our operation was successful.
A 201 status code means that our create operation was performed while 404 status code means that the resource we are looking for on the API does not exist.

For more details about status code, please refer to this article from the Mozilla developer blog here

f. Endpoints
APIs are designed to expose functionalities or services to consumers (applications, other APIs, etc.).

Imagine a simple calculator API. It offers various functionalities like addition, subtraction, multiplication, and division.

Each of these functionalities is implemented as a specific function within the API.

To enable consumers to call the right function when needed, the API uses endpoints. These endpoints act as unique URLs that map to specific functionalities within the API.

By sending requests to these endpoints, consumers can access and utilize the desired functionalities of the calculator API

Here's an example of how a calculator API might use URLs (endpoints) to expose its functionalities:

Base URL: https://api.yourcalculator.com/
Endpoints:
1. Addition:
URL: https://api.yourcalculator.com/add
Method: POST
2. Subtraction:
URL: https://api.yourcalculator.com/substract
Method: POST
3. Division:
URL: https://api.yourcalculator.com/divide
Method: POST
4. Multiplication:
URL: https://api.yourcalculator.com/multiply
Method: POST

Notice that each operation has a specific URL that identifies the desired function. That makes it easy for consumers to send requests to the correct function in the API.

g. Caching
Let's go back to our Market analogy with Mr. API again.

Imagine you loved the soft, white blouse you received for the wedding outfit and decided you want another one for a different occasion.

Instead of Mr. API running back to the vendor each time, he might have a spare blouse tucked away in his stock –** a cache.**

This cache holds onto recently retrieved items, allowing Mr. API to deliver them quicker without needing to revisit the vendor every single time.

This is API caching.

It stores frequently requested data locally within the API itself. When a similar request comes in, the API can check its cache first.

If the information is fresh and hasn't changed, it can be delivered instantly without needing to contact the original source (the vendor) again.

This saves time and resources.

h. API keys
API keys are like digital identity cards that API providers use to identify and manage API consumers (applications, other APIs, etc.) accessing their APIs.

They serve several key purposes:

  • Identification: Similar to an ID card, API keys uniquely identify the consumer and allow the provider to track their usage and activity.
  • Regulating resource usage: API keys can be used to set limits on the number of requests a consumer can make or the amount of data they can access, preventing potential abuse and ensuring fair usage for all.

  • Preventing unauthorized access: API keys act as a security measure by restricting access to protected systems. Only authorized consumers with valid keys are granted access, etc.

i. Authorization
Imagine entering a club. Just like you might need a specific ID or ticket to gain access, authorization in APIs verifies if a user or application has permission to access certain functionalities or data.
It acts like a security guard, ensuring only authorized entities can interact with the API.

j. Permission
Continuing the club analogy, specific membership types might grant access to different areas or activities within the club.

Similarly, permissions in APIs define what actions or data a user or application is allowed to access.

For instance, a "read-only" permission might allow viewing information, while a "write" permission might be needed to modify data.

k. Tokens
Think of tokens as temporary passes or keys. In the API world, tokens are short-lived credentials issued after successful authorization.

These tokens are used in subsequent requests to prove continued access without needing repeated logins or authorization checks.

l. Middleware
Imagine having a helpful assistant who intercepts messages and performs tasks before delivering them. Middleware in APIs acts similarly.

It is software that sits between the API and the application, potentially performing various tasks like:

  • Security checks: Ensuring requests are valid and authorized.
  • Data transformation: Converting data between formats for compatibility.
  • Logging and monitoring: Tracking API activity for analysis and troubleshooting .

m. JSON and XML
JSON (JavaScript Object Notation) and XML (Extensible Markup Language) are two of the most popular ways of structuring data for exchange with an API and a consumer.

When you want to send a request or when an API wants to return a response, the data must be structured in such a way that it is useful, easy to decode, etc., JSON and XML are two of the structures for doing this.

n. API Documentation
Think of an instruction manual for assembling a furniture piece. API documentation serves a similar purpose.

It's a comprehensive guide that explains how to use the API, including details on:

  • Available endpoints: The different "doors" you can knock on to access functionalities.
  • Request and response formats: What information to send and what to expect back.
  • Authentication and authorization: How to gain access and what permissions are required.
  • Error handling: How to interpret and troubleshoot potential issues.

o. Version
Just like software updates, APIs can evolve and introduce new features or changes. Versioning helps manage these changes by clearly indicating different iterations of the API.

This allows developers to stay compatible with the version their application is designed for and adapt to any updates smoothly.

Okay, so now we have to dig deeper into all the intricacies of APIs covering the history the use cases, and some common terminologies.

Now, it is time to see how API works in practice. In the next section, you will create a simple API in Python, make a request to it, and analyze its response.

By doing so, you will learn to import HTTP methods and how to use them.

Creating and Using a Simple Python API

Let's build a basic Python API to demonstrate how APIs work in practice. We'll utilize the Flask library for simplicity, although various frameworks can be used to create APIs in Python.

a. Setting Up:
Make sure you have Python and pip (package installer) installed.
If you do not have Python, you can install the latest version from the Python ecosystem here

Each Python installation comes with the pip package.

Verify your installation by running;

Python3 -- version

If your installation is successful, you should see the current python in your bash terminal.

Install the Flask library using:
pip install Flask

b. Creating the API:
Create a Python file (e.g., api.py) and paste the following code:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/greet', methods=['GET'])
def greet():
  """Greets the user with a personalized message."""
  name = request.args.get('name', 'World')  # Get name parameter from URL or default to 'World'
  return jsonify({'message': f'Hello, {name}!'})

if __name__ == '__main__':
  app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • We import the necessary modules: Flaskfor creating the API and utilities for handling requests and responses, and jsonifyfor converting Python dictionaries to JSON format.
  • We create a Flask application instance named app.
  • We define a route using the @app.route decorator, specifying the endpoint (/greet) and accepted methods (GET).
  • The greet function handles requests to the /greet endpoint.
  • It retrieves the name parameter from the URL query string using request.args.get(), providing a default value of "World" if not specified.
  • It constructs a dictionary with a personalized greeting message and uses jsonify to convert it to JSON format.
  • Finally, we run the application in debug mode, allowing for automatic reloading of code changes

c. Running the API:
Save the code in your api.py file.
Open a terminal and navigate to the directory containing your file.
Run the API using the following command:
python3 api.py

This will start the API, and you should see a message in the terminal indicating it's running on a specific port (usually http://127.0.0.1:5000/).

  1. Making a Request: Open a web browser and navigate to: http://localhost:5000/greet?name=Samuel

Replace "Samuel" with your desired name.

You should see a JSON response in the browser with the personalized greeting message:
{"message": "Hello, Alice!"}

Understanding the Process:

  • You sent a GET request to the /greet endpoint of your API.
  • The API processed the request, retrieved the name parameter, and constructed the response message.
  • The response was sent back in JSONformat, which the browser displayed

e. Analysis:

This example showcases the basic flow of an API:

  • Clients (browsers, applications) send requests to specific endpoints defined within the API (using HTTP methods like GET, POST, PUT, DELETE).
  • The API server receives the request, and processes it based on the endpoint and method.
  • The server generates a response, often in JSON or XML format, containing the requested data or a status message.
  • The client receives and interprets the response.

If you are here, congratulations, you have done a lot already. You have covered what is an API, understand common terminologies, and even created an interface with your API.

Now, there is just one more step to go.
Let's look at the step-by-step approach to creating your API

Steps to designing your API

Building an API is a deliberate process. As a designer, you should try as much as possible to cover all loopholes.

Here is a step-by-step guide to building your API

a. Define the Purpose and Goals:
What problem are you trying to solve or what functionality are you offering?
Who is your target audience (applications, other APIs)?
What data will be exposed, and what actions will be allowed?
Clearly defining the purpose and goals helps you design an API that effectively meets user needs.

b. Plan the API Design:

I.Identify resources: What data entities or functionalities will users interact with? (e.g., products, users, messages)

ii. Define endpoints: Map resources to URLs that act as entry points for accessing them. (e.g., /products, /users/me)

iii. Choose methods: Specify the HTTP methods allowed for each endpoint (e.g., GET for reading, POST for creating, PUT for updating, DELETE for removing).

iv. Determine data formats: Select a format for request and response data, such as JSON or XML.

Planning the design helps ensure a consistent and user-friendly API structure.

c. Implement the API:
I. Choose a development framework or library: Popular options in Python include Flask, Django, or FastAPI.

II. Write code to handle requests and responses: Implement logic for each endpoint, interacting with your data source (e.g., database) as needed.

III. Handle errors and authentication: Design mechanisms to gracefully handle errors and implement authentication if your API requires access control.

IV. Implementation involves translating your design into functional code using your chosen tools and frameworks.

d. Document Your API:
Create clear and comprehensive documentation:

Explain how to use your API, including endpoint details, request parameters, response formats, and error codes.

Provide code examples: Offer code snippets in various programming languages to help users integrate your API into their applications.
Good documentation is crucial for developers to understand and effectively utilize your API.

e. Test and Deploy:
Test your API thoroughly: Use various tools and techniques to ensure your API functions as expected under different scenarios. I love Postman

Deploy your API to a server: Choose a hosting platform suitable for your needs and configure access as needed.

Testing and deployment ensure your API is reliable and accessible to its intended users.

f. Maintain and Update:

Monitor API usage and performance: Track usage patterns and identify potential issues.
Be responsive to user feedback: Address any bugs or feature requests to improve your API.

Consider versioning: Implement versioning to manage changes and ensure compatibility with existing users.

Conclusion;
Wow, you got hear. I am excited that you manage to get point. If you love this article, please kindly reshare it to your community. If you found any mistake, please do well to email me here samuelkufrewillie@gmail.com. If you don't mind, you can follow me on Twitter here and on linkedin in here

Top comments (4)

Collapse
 
natescode profile image
Nathan Hedglin

APIs are NOT REST APIs.

Programming Languages have APIs, libraries have APIs, Operating System have APIs. Arduino has an API.

Application Programming Interface means there is a connection point (interface) between someone else's software (application) that you can access from code (programming).

An API is just the connection point between someone's else's code and yours

Great post but I'd rename it to "What is a REST API?"

Collapse
 
samuelkufre profile image
Samuel Kufre Willie

You are correct Nathan!!

Collapse
 
ravavyr profile image
Ravavyr

All of this is a very nice long write up about APIs and various ways these are implemented.

I would like to state though that an API is really just this:

  • the client [a computer, any device that will send a request]
  • an endpoint [any url that accepts requests and processes them and returns them]

What the client is [pc,laptop,mobile, another server] doesn't matter.
What the endpoint is [server file, custom subdomain, root domain, lambda function] doesn't matter.
As long as the information requested is received by the client.

We've called these SOAP requests, endpoints, APIs, Rest APIs, Json endpoints, XML endpoints, etc etc etc.
In the end, it's a request and a response, that's it.
KISS method applies and helps newbies understand it faster.

Collapse
 
samuelkufre profile image
Samuel Kufre Willie

You correct as well... 💪💪💪