Understanding APIs: 10 API Concepts and Examples
Tags: api, javascript, webdev, programming
Published: 2024-06-27 12:59:58

As a developer or a person in tech, you are likely to have heard of "APIs.” Hearing this term may get you curious. Imagine you're using a service that needs to fetch data from another server. APIs make this possible by serving as a bridge between the data and the application.

This article will clarify APIs by explaining the basic concepts and practices you can apply to your API development cycle. Here is a thing you should know before getting started with APIs 😂👇:


![one does not try meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8lzw28oxegw3hewvp8q.jpg)

---

<a href="https://github.com/latitude-dev/latitude" class="ltag_cta ltag_cta--branded" role="button">⭐️  Would you consider giving us a star on GitHub? ⭐️ </a>

---

## What you will learn from this article?

* Basic understanding of APIs, their key concepts, and their importance in your development cycle.
    
* Types of APIs and their fundamentals.
    
* Best practices in API development
    
* Tools or platforms where you can experiment with APIs.
    

## Introduction

APIs are one of the foundational components of modern development. They enable seamless interaction between applications and data. Instead of manually providing communication between applications and data, using APIs makes this interaction accessible and efficient for developers.

Whether you are building a web application, a mobile application, or integrating a service, APIs are crucial in allowing different components in your application to connect with your data seamlessly.

## What is an API?

An API (Application Programming Interface) is a framework that consists of a series of commands, functions, and protocols that enable interaction between different applications. Its primary purpose is to define methods and data structures developers could use to interact with their software components.

Think of API as a waiter in a restaurant; you tell the waiter (API) what you want, and they bring it to the kitchen (server) and then deliver your food (data) back to you. That is precisely how it works!


![server meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azkmbkvkjlurhs1u8ow0.jpg)

APIs serve as links that take requests from applications, fetch the necessary data from a server, and then return the processed data to the application.

## Types of APIs

There are different types of APIs tailored for various use cases and purposes. Understanding types of APIs helps developers choose the correct API for their specific needs. Here are the most common types of APIs:

* **Public or Open APIs**: These are made publicly available to any developer with little or no restrictions, enabling developers to access a service's data and functionalities.
    
    A good example of a place where you can get a public API is the [Some Random API platform](https://some-random-api.ml/). You will find a lot of API endpoints you can use freely in that service.
    
* **Internal or Private APIs**: Their primary intent is team collaboration. They are usually not open to external developers and are used to integrate systems and services within a team or an organization. They are restricted to developers granted access to work with the API.
    
    APIs are made private for many reasons. Some are made private to secure sensitive data, accelerate development for business reasons, or enhance internal workflows. If you're working on a large-scale application, it's best to protect your API by privatizing it.
    
* **Partner APIs**: This is an example of a private API; they are not open to the public. However, they are specifically designed for external partners to use. Access is typically granted through a contractual agreement, allowing partners to integrate and access certain functionalities or data.
    

Now that you know the major types of APIs, it's best to understand how and where they can be applied. Different types of APIs serve various purposes and are best suited for some specific projects.

## REST APIs

**REST** (Representational State Transfer) or **RESTful** APIs are rules for building and interacting with web applications. They rely on standard HTTP methods and protocols to enable communication between clients and servers.

REST APIs are designed to be simple, scalable, and stateless, making them popular for web and mobile applications. Unlike a typical API, RESTful APIs are not a protocol; instead, they leverage them for interaction.

![spongebob meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fqvr2kaj2zj9b09micj2.jpg)

The server responds with the requested data when the client asks for it. That's how easy it is!

## Principles of REST APIs

Some architectural principles guide RESTful APIs; their unique architecture makes up everything, ensuring they remain efficient and easy to use. Here are some of REST APIs' unique principles:

* **Statelessness**: Every request from a client to a server must contain all the necessary information to understand and process the request. The server does not store any session state about the client.  
    This helps to simplify the server's architecture, as it doesn't need to manage and store session information, making the application more scalable. It also helps to give accurate information.
    
* **Client-Server Architecture**: In a REST API, the client and server are separate components that interact through requests and responses. The client handles the user interface and user experience, while the server manages data storage.
    
* **Uniform Interface**: REST APIs follow a consistent way of getting access to resources. This includes using HTTP methods like `GET`, `POST`, `PUT`, and `DELETE` to URIs (Uniform Resource Identifier) to access and manipulate resources. This makes REST APIs easier to understand and accessible, as developers can rely on the patterns they are familiar with.
    
* **Cacheability**: This is one of the principles of RESTful APIs that most developers enjoy. With REST APIs, responses from the server are labeled as cacheable or non-cacheable. Caching can reduce the number of client-server interactions and improve performance.  
    This increases efficiency by reducing unnecessary network calls, decreasing latency, and improving overall performance.
    

RESTful APIs have a great structure, commonly used in the modern-day development cycle. Its major features are its principles, which make REST APIs what they are.


![riding bicycle rest api meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gp8lrzhnn5et5ae2cbqo.jpeg)
Image credit: [Phil Sturgeon](https://x.com/philsturgeon/status/1047527475931041792)

## SOAP APIs

**SOAP** (Simple Object Access Protocol) API is a protocol for exchanging structured information in web applications. Unlike REST, which uses simple HTTP methods, SOAP leverages XML for its message format and follows a more complex structure.

SOAP APIs are strictly used for web applications and have built-in commands to ensure the security of messages, making them suitable for applications with tight security.

### Differences between REST and SOAP

There are clear differences between **REST** and **SOAP**, as noticed in the definition above. While both are used for the web, they still differ in architecture, standards, etc. Here are some of its differences:

* **Protocol VS Architectural Style**:
    
    * **SOAP**: A protocol with standards and rules.
        
    * **REST**: An architectural style that uses standard HTTP methods and protocols for interaction between web applications and data.
        
* **Message Format**:
    
    * **SOAP**: Uses XML for message formatting.
        
    * **REST**: Uses JSON but can also use XML, HTML, or plain text for message formatting.
        
* **Complexity**:
    
    * **SOAP**: It's more complex due to its standards and XML messaging.
        
    * **REST**: Simpler and more flexible, easier to implement.
        
* **Transport**:
    
    * **SOAP**: Can use various protocols (HTTP, SMTP, etc.).
        
    * **REST**: Typically uses HTTPS for communication.
        


![jealous girlfriend meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1wb7524l1kjcwwh7qxgv.jpeg)

By understanding the differences between this protocol and architectural style, developers can choose the appropriate protocol based on the needs of their specific applications.

## JSON and XML

**JSON (JavaScript Object Notation)** and **XML (eXtensible Markup Language)** are standard API communication data formats. These formats serve the same primary purpose: to encode data structures between a server and a client so that both can understand.

### JSON

**JSON** is a lightweight data-interchange format derived from JavaScript. It is easy for humans to read and write and for machines to parse and generate.

### XML

**XML** is a markup language that defines the structure for encoding documents in a format readable to humans and machines. XML is mainly known for its ability to handle complex data structures.

### Differences between JSON and XML

* **Readability**:
    
    * **JSON**: Syntax is more readable, ideal for quick interaction, and more accessible for developers.
        
    * **XML**: Comes with a more complex syntax. Best tailored for representing complex data structures and documents.
        
* **Size**:
    
    * **JSON**: More compact and lightweight. Results in faster data transmission and less bandwidth usage.
        
    * **XML**: Larger due to extensive use of markdown tags.
        
* **Data Types**:
    
    * **JSON**: Supports data types such as strings, numbers, arrays, and objects.
        
    * **XML**: All data is written in text, requiring parsing for specific data types.
        
* **Parsing and Performance**:
    
    * **JSON**: Faster to parse, especially in JavaScript environments, due to compatibility.
        
    * **XML**: Slower to parse and process, requiring more resources.
        
* **Schema Support**:
    
    * **JSON**: JSON schema is available but not as extensive as XML schema.
        
    * **XML**: XML schema is very powerful for verifying document structure and data types.
        

You can use whichever data formats you want for communication when working with APIs. It's best to know its differences, as there is no 'perfect' data format to use in API development. You can select any of them tailored to your needs.

### When to use

There are cases where you can use JSON as your data format, as well as cases where you can use XML. Knowing when and where to use them is very important.

You can use **JSON** when:

* You need a lightweight data format.
    
* Working with web APIs, especially in JavaScript environments.
    
* Simplicity and readability are essential.
    
* You are dealing with simpler data structures and need to reduce bandwidth usage.
    

You can use **XML** when:

* You want to handle complex data structures.
    
* Validation of the data format and structure is needed.
    
* Working with applications that require extensive metadata and descriptive data.
    
* Data interchange needs to be highly extensible and self-descriptive.
    

By understanding the strengths and cases when you can use both JSON and XML, developers can decide which data format to use based on the needs of their applications.

## API Endpoints

At this point in this article, you may be wondering what API endpoints are because you might have come across the term "API endpoints" a few times in this article.

An **API endpoint** is a URL at which a client can access an API to perform actions like retrieving, updating, or deleting data. Endpoints represent the functions and services provided by an API.

The endpoint lets API interact with the application you are working on, enabling communication and exchange of information. They are accessed with HTTP methods such as `GET`, `POST`, `PUT`, and `DELETE`, which define the type of operation that will be performed.




### Example of an API Endpoint

Let's consider an example of a REST API for managing student information in a web application. The base URL for the API could be [`https://api.example.com`](https://api.example.com). Now, let's take a look at other endpoints and responses.

* **Retrieve a list of students**:
    
    * **Endpoint**: [https://api.example.com/students](https://api.example.com/students)
        
    * **HTTP method**: GET
        
    * **Purpose**: To retrieve a list of all registered students in the system.
        
    * **Request**:
        
        ```bash
        GET https://api.example.com/students
        ```
        
        Here is the response you get:
        
        ```json
        [
          {
            "id": 1,
            "name": "Opemipo Disu",
            "email": "opemipo.disu@school.com"
          },
          {
            "id": 2,
            "name": "Ralf Endrick",
            "email": "ralf.endrick@school.com"
          }
        ]
        ```
        
        In this example, we used the GET method to retrieve information from the system. After that, it gives us the data we requested from the endpoint in JSON format.
        

Another example could be an endpoint for registering students in the system. Let's create that and see its response.

* **Add a new student**:
    
    * **Endpoint**: [https://api.example.com/students](https://api.example.com/students)
        
    * **HTTP Method**: POST
        
    * **Purpose**: Adding a new student to the management system.
        
    * **Request**:
        
        ```json
        POST https://api.example.com/students
        Content-Type: application/json
        
        {
          "name": "Opemipo Disu",
          "email": "opemipo.disu@student.com"
        }
        ```
        
        **Response**:
        
        ```json
        {
          "id": 1,
          "name": "Opemipo Disu",
          "email": "opemipo.disu@student.com"
        }
        ```
        
        In this case, you will notice we are working with the [https://api.example.com/students](https://api.example.com/students) endpoint, basically because we want to add a new student to the system; the only way the users could be accessed is by using that endpoint because it should have information related to the student in it.
        
    
Now, let's think of deleting a specific student's information. Here's how we could go about that:

- **Deleting a Student's information**
    - **Endpoint**: [**https://api.example.com/students/{id}**](https://api.example.com/students/%7Bid%7D)
    - **HTTP method**: DELETE
    - **Purpose**: To delete a student by their ID.
    - **Request**:
        
        
        ```
          DELETE https://api.example.com/students/1
        
        ```
        
         **Response**:
        
    
         ```
          {
            "message": "Student deleted successfully."
          }
    
         ```
    
    When you want to delete a student's information using an API, addressing the specific data by its ID in the API endpoint ensures that you target the correct record.
    

By understanding how endpoints work and seeing some examples, developers can also use APIs to interact with web applications and perform various operations.

## **HTTP methods**

HTTP methods define the action performed on resources identified by the API endpoints. We have almost 40 registered HTTP methods, but here are the four most common ones:

- GET
- POST
- PUT
- DELETE

Now, we will go into what these methods are used for and provide an example for each of the four most commonly used HTTP methods.

### **GET**

The **GET** method retrieves data from the server without making any changes to the server data.

An example of how it works was showcased earlier in the endpoint for retrieving students' information.

An example, once again:

**Request**:

```
GET https://api.example.com/students

```

**Response**:

```
[
  {
    "id": 1,
    "name": "Opemipo Disu",
    "email": "opemipo.disu@school.com"
  },
  {
    "id": 2,
    "name": "Ralf Endrick",
    "email": "ralf.endrick@school.com"
  }
]

```

As seen above, the GET method was used to retrieve the data shown in JSON format from the endpoint.

### **POST**

The **POST** method sends data to the server to create a new resource. Unlike GET, which is used to retrieve data, POST submits data to the server. GET is dependent on the data sent to the server by POST.

An example of how the POST method could be used was explained earlier. The student's registration example was a precise instance where the POST method could be used.

If you missed it, please take a look at it again.

**Request**:

```
POST https://api.example.com/students
Content-Type: application/json

{
  "name": "Opemipo Disu",
  "email": "opemipo.disu@student.com"
}

```

We sent a request using the POST method. This was used because we wanted to add a student's information to the server.

Here's the response we get by doing that:

```
{
  "id": 1,
  "name": "Opemipo Disu",
  "email": "opemipo.disu@student.com"
}

```

In the response above, the POST method automatically helped to create and register the new student. That is just how the POST method works.

### **PUT**

This method is used to update existing resources with new data or create a new resource if it doesn’t exist. It replaces the current information of the resource with the data provided in the request.

Let's take an example of updating a student's information using the PUT method.

**Request**:

```
PUT https://api.example.com/students/1
Content-Type: application/json

{
  "name": "Opemipo Hay",
  "email": "opemipo.hay@student.com"
}

```

**Response**:

```
{
  "id": 1,
  "name": "Opemipo Hay",
  "email": "opemipo.hay@student.com"
}

```

In this case, we had to locate the information we wanted to update using its ID. We used the PUT method and added the data we wanted to update.

### **DELETE**

This method is used to delete existing resources. When a DELETE request is made, the server deletes the resource the URI identifies.

For this, we will take an example of deleting a student's information by its ID.

**Request**:

```
DELETE https://api.example.com/students/1

```

**Response**:

```
{
  "message": "Student's information deleted successfully"
}

```

In the request, we used the DELETE method to delete the user's information using their ID. After, we got a response saying, "Student's information deleted successfully."

## **HTTP Status Codes**

HTTP status codes are responses returned by servers to indicate the result of the client's request. They play a vital role in API communication by displaying the outcome of the client's request to the server.

Here are some common out of many HTTP status codes:

- 200
- 400
- 500

### **200 (OK)**

When you get this response, the request is successful, and the server returns the requested data.

An example of where you can get this response is when there's a successful GET request to retrieve data. This indicates in the **network** tab of your **developer console** that the operation was successful and that the server processed the request as expected.

### **400 (Not Found)**

You get this response when the server cannot find the requested resource or data. This could be because data wasn't fetched correctly or because the resource doesn’t exist.

An example of where you can get this error is when you use a `GET` request for a user that does not exist. Let's have a quick look at that:

**Request**:

```
GET https://api.example.com/users/583

```

**Response**:

```
{
  "status": 404,
  "message": "Resource not found"
}

```

The response gave an error because there was no resource in the presumed endpoint.

![copying answer meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3u35kypk3g7hmhu4is63.jpeg)

### 500 (Internal Server Error)

When you get this response, the server encountered an unexpected condition that prevented it from fulfilling the request.

You could get this response when a server-side error occurred while processing the request.

**Request**:

```json
POST https://api.example.com/students
Content-Type: application/json

{
  "name": "Opemipo",
  "email": "opemipo.disu@example.com"
}
```

**Response**:

```json
{
  "status": 500,
  "message": "Internal server error"
}
```

A **500 Internal Server Error** indicates a general server-side error. It shows that something went wrong on the server, not necessarily due to the client's request.

While there are a few other HTTP status codes, [you can read this article to learn more about them](https://www.geeksforgeeks.org/10-most-common-http-status-codes/). The ones available in this article are the most common status codes.

## **Authentication and Authorization**

While API security is essential, authentication and authorization are critical components of API security. Authentication in API development is the process of verifying the identity of a user or an application, typically through techniques like API keys, OAuth tokens, or user credentials.

Authorization, on the other hand, determines what resources or operations the authenticated entity is allowed to access.

These processes ensure only valid users or applications can access the API and perform actions based on their permissions.

### Basic Concepts of API Keys and OAuth

An **API key** is a unique identifier used to authenticate requests associated with a project or application.

API keys are included in the API requests to identify the calling project or application. They are typically used to track and control how the API is being used. API keys should be kept secure and not exposed in code to prevent unauthorized access.

However, they are not secure and should be used with other security measures, such as environmental variables.

On the other hand, **OAuth** (Open Authorization) is a token-based authentication framework that allows third-party applications to access user data without exposing user credentials.

It is widely used by platforms like Google and GitHub to grant limited access to user data. It involves a flow where the user authorizes the application, and the application receives an access token that can be used to make authorized API requests. It provides a more flexible and secure method compared to API keys.

### Importance for API Security

* **Prevention of Unauthorized Access**: Authentication ensures that only users and applications can access the API, preventing unauthorized access to sensitive data.
    
* **Rate Limiting**: Authentication helps track APIs' usage, enabling the implementation of rate limits to prevent data misuse.
    
* **Monitoring**: Authentication allows for detailed logging and monitoring of API usage, which can be crucial for identifying errors.
    

## Rate Limiting and Throttling

APIs use rate limiting to keep things stable and safe. This means they limit how many requests a user or application can make in a certain amount of time. This helps prevent servers from getting overloaded.

It also ensures that all users in an application get an equal distribution of the API's resources.

To manage rate limits, applications should gradually increase the wait time between retries if a limit is reached. Monitor your API usage to stay within these limits. If you store frequently used data, you can reduce the number of requests you make.

Using page numbers and filters can help you manage large data sets more quickly, reducing the load on the API.

## **Testing APIs**

Testing APIs is essential in the API development process, ensuring that your application communicates correctly with the server and handles data as expected. Dedicated tools allow you to make API requests, check and analyze responses, and log issues early in the development cycle.

Let's explore some of the best tools for testing APIs and provide an essential guide on effectively testing an API using these tools.

### API testing tools

* [**Postman**](https://www.postman.com/)**:** Postman is a tool that simplifies API development. It allows you to construct and send requests, organize APIs into collections, automate tests, and generate detailed reports.
    
    Ideal for both manual and automated testing, Postman supports various HTTP methods, making it flexible for testing.
    
* [cURL](https://curl.se/)**:** This command-line technique enables data transfer with URLs.
    
    cURL is used mainly because of its accessibility and flexibility, especially for developers comfortable with the command line.
    
* [**Swagger**](https://swagger.io/)**:** Swagger provides a suite of tools for API documentation and testing. It allows you to visualize and interact with the API's resources without manually creating requests.
    

### **Guide on how to Test an API**

1. **Define the Endpoint and Method**
    - Determine the API endpoint you wish to test and the HTTP method (GET, POST, PUT, DELETE) to use.
    - Example: To fetch user data, you might use:
        
        
        ```
          GET https://api.example.com/users
        
        ```
        
2. **Set Up the Request**
    - **Postman**: Open Postman, create a new request, enter the endpoint URL, and select the HTTP method. Add necessary headers like API keys and parameters.
        
        For a GET request to retrieve users, just set the URL to [**`https://api.example.com/users`**](https://api.example.com/users) and include any required headers or parameters.
        
3. **Send the Request**
    - Click "**Send**" in Postman to execute the request and observe the response.
4. **Analyze the Response**
    - **Status Code**: Indicates the success or failure of the request (e.g., 200 OK, 404 Not Found).
    - **Headers**: Provide metadata about the response.
    - **Body**: Contains the data returned by the API, typically in JSON or XML format.
    - **Example**: A successful GET request might return a status code 200 and a JSON body with user data.
5. **Handle Errors**
    - If the request fails, analyze the status code and error message to diagnose the issue.
        - **Example**: A **404 status code** indicates that the endpoint is incorrect or the resource does not exist.
    - Adjust the request accordingly and retry.
6. **Automate Testing**
    - Postman supports scripting to automate tests. You can write pre-request scripts to set conditions and test scripts to validate responses.
        - **Example**: To verify a successful response, add the following script in Postman's "Tests" tab:
            
            
            ```
              pm.test("Status code is 200", function () {
                  pm.response.to.have.status(200);
              });
            
            ```
            

By utilizing tools like Postman, cURL, and Swagger, you can streamline the process of testing APIs, ensuring your application interacts with external services reliably and efficiently.


## **Conclusion**

Understanding APIs is essential for any developer who is just starting. They are a major component of modern development, enabling seamless communication and data exchange between applications.

This article has covered the fundamental concepts of APIs, including their types, key principles of REST and SOAP APIs, data formats like JSON and XML, and the importance of API endpoints and HTTP methods.

Additionally, we explored aspects of API security through authentication and authorization, as well as the importance of rate limiting and throttling.

If you found this article helpful, please consider giving us a star on GitHub

[⭐ Would you consider giving us a Star on GitHub?⭐](https://github.com/latitude-dev/latitude)


![thank you gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/an3sgmfqrn9p5s07a6dj.gif)

Your support helps us to continue improving and providing valuable content to the developer community. Thank you for reaching this far in this article 💙!