API for Dummies: What is an API, How Do They Work?

API for Dummies: What is an API, How Do They Work?

API for Dummies: What is an API, How Do They Work?

Have you ever wondered how apps and websites work together seamlessly? Well, this is where the power of APIs comes into play. The full form of API is Application Programming Interface. In simpler words, we can define it as a tool that helps different applications talk to each other without disturbing the backend processes. For example, if you are using your travel app, it does not just show you flight prices. At this moment, it is using another server with the help of an API to fetch data for you. Another example is when you try to log in to your Gmail account using another device. This process involves different APIs working in the background.

If you have been looking for an easy API guide for dummies, this is for you!

What is an API? 

Before moving on to the API tutorial for beginners, let us briefly discuss the question of “What is an API?”

An Application Programming Interface can be defined as a set of rules, which works as an intermediary between two or more applications. Suppose you, as the client, want to buy beef meat from the store, which will be procured from the farm. The store, in this case, does not need to know the inner working of the farm to deliver fresh meat to the client. This is the same with the API, which works as an intermediary to simplify the process and enhance the communication between two or more software. Nowadays, the applications are efficient because the API does work in the background. For instance, if you want to check the weather or book a taxi with the help of your smartphone, the API works as an intermediary to fetch the data between two or more platforms.

Here are some terms associated with API basics, which are crucial in understanding how API works:

  • API Call: An API call is also known as an API request. It is a message to a server to enable an API to execute an action. It is the API call that starts an action requested by a client on a website or application.
  • API Key: An API key is of major significance when it comes to authenticating an API call. In other words, it is used to identify an application before communication is established to ensure security of data.
  • API Gateway: API gateways are used to process information from the client side to the server end. It is through API gateways that requests are processed and forwarded to various servers to generate a response to the client. Therefore, API gateways help coordinate action to ensure that requests reach the right servers and a response is sent to the client.

How does an API work?

How does an API work

In this section, we are going to answer the most asked question: how do APIs work? It is important to understand how APIs work, especially for developers, because it is the point of contact for your project and already existing systems. In order to understand API meaning, we should note that API works on the request-response model. This is to say that the client sends a request to the API server, and then the API receives the response from the server. In terms of steps, there are functional HTTP requests and API endpoints.

Here is the process:

API Client

The client starts by making a request to the API server. The client sends an HTTP request, and it may be in various formats like GET, DELETE, PUT, or POST. For example, you may like to enter a GET request like “what is the temperature in Canada today?” Additionally, it may be initiated by another event like notification from another connected application.

API Request 

An API request will look different depending on the API. Nevertheless, it is made of various parts like endpoint, method, parameters, headers, and body. An endpoint is used for communication and is often represented as a URL. It is where the API gets requests. On the other hand, the methods used in the request are the communication language used by the client to tell the server what it wants to do with the data. In addition, the parameters used in the API are what define the API call. They are used to create unique endpoints for the API call. They can be represented in the request body, headers, and URLs.

On the other hand, request headers are part of the HTTP request and often used for communication. They give more information concerning the request and its expected outcome. They are often in key-value pairs.

Lastly, there is a request body that is considered the main component of an HTTP request. Most of them are seeded with create and update operations such as POST, PATCH, and PUT. For instance, when creating a new user account, there is a possibility that the user’s details such as their name, email, and password are contained in the request body.

API Server

The API server receives requests from the API client. It is in charge of handling requests from the client end and responding appropriately. The API server carries out various operations such as authentication of responses, validation, extraction, and manipulation of data.

API Response

Lastly, there is a component known as the API that receives a response from the server and transmits it to the client. Most of the responses are usually accompanied by a status code that reflects the status of the sent requests. Checking the status of HTTP requests is important in API development in case of any error occurrences in either the server end or client applications. Below are various status codes relating to the API for beginners:

  • 200 “OK” – means the request has been successful.
  • 201 “Created” – confirms the creation of the resource has been successful.
  • 202 “Accepted” – means the request has been accepted for processing.
  • 404 “Not Found” – means the server could not find the page.
  • 500 “Internal Server Error” – means the server has encountered an unexpected error.

Another important aspect of the API response is the header. Although the header appears similar to the request header, the API response header offers additional information on the server’s response. Finally, the API response body contains the information the client has requested or an error message if the request cannot be processed.

Benefits of API

APIs enable software systems and applications to communicate effectively. Some of the advantages of API include:

Automation

The use of APIs helps in the automation of repetitive tasks, which are usually time-consuming. This, in turn, helps humans to direct their energy towards more complex tasks. Through the use of APIs, the workflows are executed consistently, which helps in improving productivity.

Security

The use of APIs helps in improving the security of the system. This is because the API can be set up to ensure that only certain individuals, such as those with the API key, are able to access the system. This helps in improving security, as an additional layer of security is created against unauthorized use of the system.

Innovation

Another advantage of the use of APIs to businesses is the aspect of innovation. Through the use of APIs, businesses are able to obtain data from various sources and analyze the data, which helps in the generation of insights for decision-making. This helps in improving decision-making processes, making them faster and smarter. Moreover, the use of APIs helps developers in building on existing frameworks, which helps in improving development.

Types of API

Types of APIs based on Architectural Styles

There are several ways of classifying APIs, but in this section of the API explanation for dummies, let us discuss the organizational types of API, which focus on the aspect of access.

Private APIs

The first type of API to look at is the ones that are only used for internal communication within an organization. This kind of API is often referred to as the internal API. They are mostly used for linking different software within an organization.

This means that they are not for use by third parties. You should be aware of the fact that there are some applications that have several dozen of these types of API for them to function effectively.

Public APIs

On the other hand, the public API offers the organization’s data flow to the public. This means that the organization’s data flow will be accessible to the third-party developers, and they will be able to integrate their own applications with the organization’s data flow.

Although some public APIs are free to the public, others are listed as billable products. For instance, an author’s platform might use the public payment API, such as the Stripe API, for payment processing.

Partner APIs

This API, as the name suggests, enables the communication of two or more organizations, making the collaboration process much easier. Only the authorized personnel of the two or more organizations can access the data on the API. This means that the API comes with the authentication parameters, which restrict the API’s access to the general public.

Composite APIs 

This API combines the use of many APIs on different servers, creating a simple API connection to meet the specific requirements of the organization. For instance, the hospital’s digital platform might be developed using the composite API, which combines the use of many APIs on different servers, such as the medical records API, billing API, and appointment API.

Types of APIs based on Architectural Styles

Another way to classify APIs is through architectural styles. Some of the most used architectural styles for API explained for dummies are:

REST API

REST API is possibly the most used API style for web programming. The reason for their popularity is their simplicity and scalability, along with their ability to integrate with different applications. It is based on a stateless architecture, which means that all the information is sent with the API call and does not depend on previous calls.

In addition, the REST API is used for applications that involve data transfer. In other words, the API server receives the request and sends the content from the target server to the user. The API uses HTTP methods such as GET, PUT, POST, and DELETE to process the data. Moreno, the requested information is sent to the client-server either in JSON or XML format

SOAP API

Simple Object Access Protocol-SOAP API uses XML protocol to enable client and server systems to communicate. Unlike REST, which is based on a stateless architecture, SOAP is based on a strict standard.

It also provides security measures that are suitable in industries that are considered to be high-risk, such as healthcare, banking, and finance. SOAP APIs are considered to be complex and require a lot of bandwidth, thus making it slow. It is mostly used in applications that require security in data exchange in a communicating system.

WebSocket API

WebSocket APIs provide two-way communication in client and server systems. Unlike REST and SOAP, which require repeated requests to communicate, WebSocket provides a constant channel of communication to update data in real-time. WebSocket API is mostly used in applications that require quick exchange of data.

GraphQL API

GraphQL API is an open-source query language. This is an alternative to REST, allowing clients to retrieve only the data they need. GraphQL enables clients to use only one endpoint to retrieve data, rather than having to send multiple requests.

Therefore, it is easier to avoid the transfer of unnecessary data between the client and the server. As a result, GraphQL API is suitable for use in applications that handle complex data. It is normally used in applications and websites where speed matters.

Remote Procedure Call APIs

RPC APIs were created by Google. This API allows a client to invoke a server like it is a local function call. This makes it easier for systems to communicate with each other.

This API is suitable for use in applications where speed and efficiency are necessary. An example of an application where this API can be used is in the RPC framework developed by Google, for use in microservices.

Step-by-Step Guide to Build an API

For the purpose of this guide, we will build a simple REST API with Python and Flask. With this, you can check the menu, place an order, and get the bill.

Here is a step-by-step guide to get it done:

Step 1: Choose a programming language and framework

Python is one of the most commonly used programming languages to build scripts. Python is simple, easy to set up and has a clear syntax. On the other hand, Flask is a light-weight web framework that makes it easy to build an API with a few codes.

Step 2: Create your coding environment

The next step is to set up your environment. We will use uv, a modern Python toolchain that is quickly replacing the old pip + venv. You can install uv via the  official documentation. Once installed, create a new project and install Flask with the following codes:

# Create project folder and enter it
mkdir bar-api && cd bar-api

# Install Flask with uv (uv manages a virtual environment for you)
uv pip install flask

Step 3: Create the first endpoint

Now, we can write a simple Flask app that acts like a bar API. First, create a new file named app.py and paste the code:

 

Flask app example (menu, orders, and billing endpoints)


from flask import Flask, jsonify, request

app = Flask(__name__)

# Sample data: drink menu
menu = [
    {"id": 1, "name": "Root beer", "price": 5.0},
    {"id": 2, "name": "Ginger ale", "price": 6.5},
    {"id": 3, "name": "Tequila", "price": 7.0},
]

# Empty list to store orders
orders = []

# Home route
@app.route('/')
def home():
    return "Welcome to our bar!"

# GET /menu — fetch the menu
@app.route('/menu', methods=['GET'])
def get_menu():
    return jsonify(menu)

# POST /order — create a new order
@app.route('/order', methods=['POST'])
def place_order():
    new_order = request.get_json()

    if not new_order or "name" not in new_order or "price" not in new_order:
        return jsonify({"error": "Invalid order data"}), 400

    new_order["id"] = len(orders) + 1
    orders.append(new_order)

    return jsonify({"order_id": new_order["id"]}), 201

# GET /bill/<order_id> — get the bill for a specific order
@app.route('/bill/<int:order_id>', methods=['GET'])
def get_bill(order_id):
    order = next((o for o in orders if o["id"] == order_id), None)

    if order:
        return jsonify({
            "order_id": order_id,
            "total_price": order["price"]
        })

    return jsonify({"error": "Order not found"}), 404

if __name__ == "__main__":
    app.run(debug=True)

Here is a breakdown of the code:

  • Flask creates the web app and manages routes (endpoints like /menu or /order)
  • @app.route() defines what each URL does and which HTTP method it supports
  •  Jsonify() is responsible for converting Python data into JSON format
  • request.get_json() reads incoming data after sending a POST request
  • return (data, 201) indicates that the order was successfully created
  •  app.run(debug=True) initiates the Flask development server

To run it:

uv run python app.py

Result: Your API is now live at http://102.1.1.0.1000/

Step 4: Test your API

Before going live, it is necessary to test the API performance. You can use curl – a command line tool for sending HTTP requests to run the API. Once your Flask server is active, open a new terminal window to use curl.

For example:

To visit the server homepage – (using GET request)

curl http:// 102.1.1.0.1000/

The response should be something like:

“Welcome to our bar!”

Step 5: Error Handling

Now that we have confirmed that our API is working as intended, it is time to make it smarter. In real-life scenarios, APIs do not only handle straight-forward requests. Therefore, you need to ensure that the API can effectively handle errors and return appropriate responses.

An example of an error is sending an HTTP request for a non-existent drink. The system sees it as an error and returns a generic HTML error response page. However, we want all responses to be in the JSON format. To achieve this, we need to add some lines of code to the bottom of the app.py file as follows:

 

Error handling example (Flask)


@app.errorhandler(404)
def not_found(e):
    return jsonify({"error": "Not found"}), 404

@app.errorhandler(400)
def bad_request(e):
    return jsonify({"error": "Bad request"}), 400

@app.errorhandler(500)
def server_error(e):
    return jsonify({"error": "Internal server error"}), 500

Here is a breakdown of the codes:

  • An HTTP error response code 404 is returned if the route does not exist. The message is in JSON format instead of an ugly HTML error response page.
  • A 400-status code is returned if the request is invalid – missing fields or wrong data
  • In the case of an unexpected error on the server, it returns a simple response code 500 in readable format

API Keys vs Bearer Tokens vs OAuth

API keys, bearer token, and OAuth play crucial roles in API security. Knowing their differences helps you understand when to use each of them. Let us explain them in details

API Keys

An API key is an alphanumeric string of code that an API server can use to identify an API caller and validate their authenticity. The primary purpose of an API key is to identify caller and determine if they are authorized for access. They are often employed in analytics, rate limiting, and usage monitoring.

Additionally, API keys are static which makes them less secure. When compromised, it grants access to anyone until it is manually rectified. They also have a longer duration, unless set to expire at a specific period.

Since API keys are an excellent way to confirm an API caller’s identity, they are ideal for:

  • Server-to-server communication: This ensures that communication is only between authorized servers.
  • Public API access: API keys are usually employed for granting access to public APIs such as Google map APIs.
  • Third-party integrations: API keys are used for third-party integrations of your API without sacrificing the ability to monitor usage and troubleshoot. This is especially useful when monetization and rate limiting are part of your objectives.

However, an API key is not efficient as a single security solution. Instead, it should be part of a broader API security structure.

Bearer Tokens

A bearer token is a security token that grants access to its holder. It means that anyone who has the token gets unrestricted access. Think of it like a movie ticket – whoever holds it gets access to the cinema without any other proof of verification.

Bearer tokens are usually associated with a specific permission or user session. Unlike API keys, they have a short duration and often expire within minutes or hours. However, they are more secure than API keys, especially when used with HTTPS.

Bearer tokens come in different formats such as:

  • JSON Web Tokens (JWT): These tokens are cryptographically signed and enable stateless authentication making them an excellent choice for distributed systems and microservices
  • Opaque tokens: These are random strings with no association to client-server. Although they are easy to implement, they require server-side storage.
  • Refresh tokens: They are designed to enable holders get new access tokens without the need for revalidation.

Some of the use cases include:

  • Microservices communication: Bearer tokens ensure secure service-to-service communication. Here, one service authenticates its request to another service using a bearer token.
  • Stateless session management: These tokens allow servers to authenticate requests without saving session information, which is great for distributed systems.
  • Mobile app authentication: Bearer tokens allow users to access app functions without the need for re-authentication.

OAuth (Open Authorization)

OAuth is an open-standard authorization protocol. It allows servers that are not directly integrated to provide authenticated access to information. This protocol allows users to authorize one application to interact with another, on their behalf without giving away their authentication credentials.

OAuth has a more complex implementation than API keys. It requires explicit user consent for the application to access specific data, which makes them highly secure. They are short-lived access and refresh tokens generated through a dynamic framework.

OAuth works via a delegation mechanism – users rely on an authorization server to generate access tokens which can be used to log in to other applications. For example, a Gmail user would like Facebook to access their contact list without sharing their mail username and password.

Recap

In this API explained for dummies article, we have learned how APIs work, their types, and their benefits to businesses. Application Programming Interface – APIs is a vital component in building applications and websites.

APIs facilitate smooth interaction between applications, help in automation, and offer additional security. Whether it is retrieving information about the weather, logging into our accounts, or making transactions in online shopping sites, APIs are hard at work to facilitate smooth interaction.

FAQ

What is an API?

An API is a tool that lets apps communicate and exchange data automatically. It simplifies integration and automation. Floppydata provides one of the easiest and most powerful APIs for beginners and professionals.

How does an API work?

It sends requests to a server and returns data in real time. Floppydata’s API allows full control, automation, and seamless integration into workflows.

Try Floppydata Proxies Now - As Low As $1/Gb

Share this article:

Table of Contents

Proxies at $1
Get unlimited possibilities

You may also like:
Ready to experience transparent and reliable proxy service?
Fast, secure, and hassle-free proxies tailored for your needs​