Theoretical concepts of APIs

Theoretical concepts of APIs

Here's my best attempt to introduce the readers to all the theoretical concepts one needs to know about APIs to build a foundation layer before diving into it, technically.

Let's get started, shall we?

Types of APIs:

There are many types of APIs, but majorly only two types of APIs are used by developers. Those are

  • REST APIs

  • SOAP APIs

Let's learn more about these 2 types of APIs.

Simple Object Access Protocol (SOAP) APIs

SOAP is simply a protocol which was designed way before REST came into the picture.

The main idea behind designing soap was to ensure that programs that are built on different platforms and programming languages like Java and Python could really exchange data in a very easy manner.

SOAP stands for 'Simple Object Access Protocol, so we can say that

SOAP is a messaging protocol specification for exchanging structured information that is Data in the implementation of web services and Computer networks.

Representational State Transfer (REST) APIs

REST was designed specifically for working with components such as media components files or even objects on a particular hardware device.

Any web service that is defined on the principles of REST can be called a Restful web service.

Now a Restful web service would use the normal HTTP verbs of GET, POST, PUT and DELETE for working with required components.

Since REST stands for Representational State Transfer, we can say that:

A REST API is simply an application programming interface that confirms the constraints of REST architectural style and allows for interaction with RESTful web services.

SOAP requires more bandwidth and computing power that's where it lags behind and on the other hand, REST requires very few resources which makes it a bit more powerful and efficient. Hence, REST is majorly used for public APIs web services, mobile services and social networks.

REST v/s SOAP

REST APIsSOAP APIs
Majorly RESt APIs are booming these days.SOAP APIs aren't used much these days.
Codebases are lighter.Codebases are heavy.
Need to code more to build these.Need less amount of coding.
Provide a feature for storing cache for faster reloads.Doesn't provide caching.
Not much secure but we can add layers to increase its security.Very secure by default

We can see that SOAP APIs are just like keeping our message inside an "envelope" and sending it to someone else but REST APIs are like writing your message on a plain "postcard" and sending it to someone else.

  • In the first case, the postman can't read the message, only the receiver reads the message.

  • In the second case, the postman can also read the message and the receiver will also be reading the message.

What does an API consist of?⚛️

Suppose https://api.publicapis.org/entries is an API URL or URI (Uniform Resource Identifier) which shows the following information on the web.

1. An endpoint

This is the URL or URI (Uniform Resource Identifier) that represents the location of a specific resource or service. The endpoint is the starting point for the API request.

For Example: In the above API URL it is giving us the results for a particular service called 'entries'

2. A Method

This is the HTTP verb that is used to make the API request, such as GET, POST, PUT, or DELETE. Each method is used for a specific purpose, such as retrieving data or updating a resource.

Learn more about API methods here: https://restfulapi.net/http-methods/

MethodDescription
GETRetrieve information about the REST API resource
POSTCreate a REST API resource
PUTUpdate a REST API resource
DELETEDelete a REST API resource or related component

3. Header

This is a collection of key-value pairs that provide additional information about the API request or response. Headers can be used to pass authentication tokens, specify the format of the data being sent, or set other options.

  • For example: Let's say you're building an API for a weather app. The app requires users to authenticate with an API key before they can access the data. You would include the API key in the headers of the API request, so the server can verify the user's identity. Here's an example of how the headers might look in Python using the requests library:
import requests

headers = {
    "Authorization": "Bearer {API_KEY}",
    "Content-Type": "application/json"
}

response = requests.get("https://weather-api.com/current-temp/{city-name}", headers=headers)
  • In this example, the "Authorization" header is being used to pass the API key to the server, while the "Content-Type" header is being used to specify that the data being sent is in JSON format.

4. Body

This is the payload of the API request or response, and it typically contains the data that is being sent or received. The format of the data in the body will depend on the API, but it could be in JSON, XML, or some other format.

  • The data might be in JSON format, for example:
{
"name": "John Doe",
"email": "johndoe@example.com",
"password": "password123"
}

5. Parameters

These are additional pieces of information that can be passed along with the API request. They can be used to specify the exact resource or action being requested or to filter the data that is being returned.

  • If you're building a search feature for a product catalogue, you might include parameters in the API request that allow the user to filter the results by category, price, or other criteria. The parameters might be included in the endpoint as query strings.

  • For example: "products-api.com/search?category=books&.."

6. Status Code

This is a three-digit HTTP status code that is returned with the API response. The status code indicates the outcome of the API request and can be used to troubleshoot issues.

  • For example, a status code of 200 indicates that the request was successful and the data was returned. A status code of 404 would indicate that the requested resource could not be found.

  • Learn more about status codes here.

Types of API Requests 💯

API requests are requests made to an Application Programming Interface (API) to retrieve or manipulate data.

An API request is typically made by a client application (such as a web or mobile app) to an API endpoint (a specific URL that represents a resource or collection of resources) to retrieve or manipulate data.

1. GET:

A GET request is used to retrieve information from the server. It is the most commonly used HTTP method and is often used to retrieve information from a website or API.

POST:

A POST request is used to send data to the server, usually to create a new resource. It is often used to submit a form on a website or to create a new object in an API.

PUT:

A PUT request is used to update an existing resource on the server. It is often used to update an existing object in an API.

PATCH:

A PATCH request is used to partially update an existing resource on the server. It is often used to update specific fields of an existing object in an API, rather than replacing the entire object.

  • A client application sends a PATCH request to an API to update a specific field of an existing user, such as the user's email address.

  • Example: PATCH https://example.com/api/users/1

DELETE:

A DELETE request is used to delete a resource on the server. It is often used to delete an object in an API

  • A client application sends a DELETE request to an API to delete an existing user. The API responds with a message indicating that the user has been deleted.

  • Example: DELETE https://example.com/api/users/1

Difference between PUT & PATCH methods:

🌟 The PUT method is used to completely replace a resource on the server with new data. When making a PUT request, the client must send the entire updated resource in the request body, including all fields, even if only a few fields are being updated.

🌟 PATCH: The PATCH method is used to partially update a resource on the server. When making a PATCH request, the client only needs to send the fields that are being updated in the request body, rather than sending the entire resource.

More about 'Status Codes' 🔢

HTTP status codes are three-digit numbers returned by an HTTP server in response to a client's request. These codes indicate the status of the requested resource and the outcome of the request.

Each status code has a specific meaning and can be used to determine the next steps in handling the response.

For example:

Status code rangeDescription
1xx (Informational)The request was received and continuing the process.
2xx (Successful)The request was successfully received, understood, and accepted.
3xx (Redirection)Further action needs to be taken in order to complete the request
4xx (Client Error)The request contains bad syntax or cannot be fulfilled by the server
5xx (Server Error)The server failed to fulfil a valid request.

How is an API made? ⚡

When building an API, it's common to use a pattern called the "Model-View-Controller" (MVC) pattern, which helps to separate the different concerns of the application.

In the context of building an API, this pattern can be adapted to be a "Model-Route-Controller" (MRC) pattern.

Model:

  • The model represents the data that the API will work with.

  • This can include the structure of the data (e.g., the fields and types of a "user" model) as well as any validation or constraints that need to be applied to the data.

  • Models are typically implemented using object-relational mapping (ORM) libraries such as Mongoose, Sequelize etc.

Route:

  • The route defines the endpoints that the API will expose and maps them to the appropriate controllers.

  • A route is typically defined using routing libraries such as ExpressJS, Flask etc.

Controller:

  • The controller handles the incoming requests and interacts with the models to perform the requested actions (e.g., creating a new user, and retrieving a list of users).

  • Controllers are typically implemented as functions or classes that take the request and the response objects as arguments.

When a client makes a request to the API, the request is first received by the route -> The route then checks the requested endpoint and maps it to -> the appropriate controller -> The controller then performs the necessary actions (e.g., validating the request data, interacting with the models) and sends -> a response back to the client.

API Security 💀

API security is important to ensure that sensitive data is protected from unauthorized access.

Here are some common security measures and terms used when building APIs:

HTTPS:

HTTPS (HTTP Secure) is a protocol for securely communicating over the internet. It uses SSL/TLS encryption to secure the connection between the client and the server.

  • HTTPS is important for protecting sensitive data, such as user login credentials, from being intercepted by third parties.

Password Hash:

A password hash is a one-way encryption of a password, which makes it more difficult for an attacker to steal a user's password if they gain access to the database.

  • When a user creates an account or changes their password, the password is run through a hashing algorithm, which creates a unique hash value that is stored in the database.

  • When the user logs in, their entered password is hashed and compared to the stored hash value.

API Key in URL:

Some APIs use a unique key that is passed in the URL to authenticate the client.

  • This key is typically generated by the server and is required for the client to access the API.

  • The key is passed as a query parameter in the URL and is checked by the server for each request.

OAuth:

OAuth is an open standard for authorization that allows a user to grant limited access to their resources to another website or application.

  • OAuth enables an application to obtain limited access to a user's account without the user sharing their login credentials.

Timestamp:

A timestamp is a way to record the date and time at which a particular event occurred.

  • In the context of API security, a timestamp can be used to validate that a request is not too old or has not been replayed.

  • This can be done by including a timestamp in the request and then checking it against the current time on the server.

Note: These are some of the common security measures and terms used when building APIs, but it's important to note that security is an ongoing process and it's important to stay updated with the latest best practices and technologies. 👩🏻‍💻


So, this is it for all the theoretical aspects of APIs, I tried to compile everything in laymen's language as I was learning about these topics myself. I'll be referring to this blog endless times to look back and revise the topics too.📝

Do let me know your feedback in the comments section. I'll be happy to read them. 😄🌟

Keep Learning!!!🥳