REST API Clarified

REST API Clarified

  • Introduction

You guys are welcome to another technological informative article. In this article, we're going to talk about what a REST API is. I am sure this might not be the first time you are hearing of APIs or REST APIs to be exact.You probably might have read and watched a couple of videos about it, still there's lots of confusion on how they really work roaming your mind. Don't fret, that's why this article is for you - it aims to bring clarity and insight to your perspective.

Now, I try to explain things on a more basic level, and hopefully that's why you guys are reading this article. I try to take complicated concepts and explain them in simple analogical terms. Sophistication doesn't align with the preferences of most people, so I like things spelled out in the most simple ways.

  • APIs Explained

Before we get into REST, let's talk about what an API is in general. So it stands for Application Programming Interface, and that's a very broad term. There's all kinds of APIs, examples are : Private APIs, GraphQL APIs, Payment APIs, Hardware APIs, RESTful APIs etc. But we're specifically talking about web APIs. There are APIs in your computer operating system, in your smartphone, and even in some refrigerators. So this is very generalized, but it's essentially a contract provided by one piece of software to another piece of software. It usually consists of a structured request and then a structured response. Hence a particular software can request for a set of information in a specific kind of way and I'll give you this data or this function or whatever that response may be.

Analogies to Help You Understand Better

To help you understand, we're going to take a look at a couple of analogies. Think of your school's library as a server with all the books and resources. You, the student, are like a piece of software (e.g., your brain) looking for information. The librarian functions as an API. You make a specific request for a book (like a request to an API), and the librarian knows where to find it, retrieves it, and hands it to you. The librarian is the intermediary, just like an API, making sure you get the information you need from the server (library). So, just like a librarian in a library, an API acts as the intermediary that fetches and delivers what you asked for, connecting your 'student software' to the 'server' of knowledge.

Another good analogy is this; in the realm of politics, think of an API as a diplomatic ambassador. Each country (system or software) has its own way of doing things, but when they need to communicate or share information, they send their ambassador (API) to ensure a smooth and standardized exchange of messages and data, bridging the gap between different systems. So this is similar to how an API works, and you can think of the ambassador as the API standard, whether it's GraphQL or SOAP or something else.

  • What RESTful API Entails

    So hopefully, those Analogies gave you a good idea of what an API is in general. Now that we've talked about what an API is, let's talk about REST. REST stands for Representational State Transfer, and it's an architecture style for designing network applications. It works by relying on a stateless client-server communication protocol, and in almost all cases, this is going to be HTTP(Hypertext Transfer Protocol).

HTTP is basically the foundation of data communication and information exchange on the World Wide Web. Every time you load a web page in your browser, it's making an HTTP request to a server somewhere. It is possible to use other protocols with REST, but HTTP is by far the most used because, in order to use real-world REST, you need the delivery methods that HTTP offers.

REST allows us to treat objects on the server side as resources that can be created, updated, and destroyed or deleted. Imagine a server-side object as a library book. Books are stored in a library. You can check out a book (GET request) to read it, return a book (DELETE request) to remove it from your possession, or even add a new book (POST request) to the library's collection , and so on.

  • Importance of REST API

REST API makes de­veloping easier by se­tting standard rules for web service­s to talk to each other. It gives de­velopers a way to work with serve­r-side info and features in a ste­ady, expected way. REST API make­s web apps more scalable and fle­xible. Because it's state­less, there's no ne­ed for the serve­r to save session info. This means multiple­ servers can manage re­quests at once. Even with a lot of traffic, it still works we­ll. REST API supports loose ties betwe­en the client and se­rver. They can grow separate­ly. So, server changes don't me­ss up existing client setups. This fle­xibility means develope­rs can add new stuff, make old stuff bette­r, and adjust to new needs without disturbing the­ user's experie­nce.

  • The Awesomeness of REST

What makes REST so awesome is that it operates using just HTTP and usually some kind of standard like JSON(or JavaScript Object Notation is used to format the data that is often exchanged through APIs), so it can be used by virtually any programming language because most of the good languages can make HTTP requests in some way, whether it's PHP, JavaScript, Rails, Java, Python, all of these languages are perfectly capable of working with RESTful interfaces.

So, hopefully, I haven't lost you yet. Just remember, an API is the messenger, and REST lets us use HTTP requests to format those messages. You may also hear the term RESTful API, and that just refers to conforming to the REST constraints. REST API and RESTful API are basically the same thing.

Now that we've established what a REST API is, let's look at the specific methods and requests that can be made to a server through HTTP. Okay, so a GET request is the most common. Your browser client makes GET requests every day just by going to a specific server URI. GET requests are used to retrieve data from a specified resource.

import requests

api_url = 'https://api.example.com/data'  # Replace with the API URL

try:
    response = requests.get(api_url)
    data = response.json() if response.status_code == 200 else f"Error: {response.status_code}"
    print(data)
except requests.exceptions.RequestException as e:
    print(f"Request Exception: {e}")

Replace 'https://api.example.com/data' with the actual URL of the API you want to make a GET request to. This code sends a GET request, handles success by printing the retrieved data, and handles errors by printing the status code.

Next, we have a POST request, and you probably use these every day as well because every time you fill out a web form, you're making a POST request. In most cases, you can also make GET requests from forms, but it's not secure, and the data you submit can be seen by anyone. Form tags in HTML can take an action and a method attribute, so the action would be the page you're submitting to, and the method would be either POST or GET.

import requests

url = 'https://example.com/submit'
data = {'field1': 'value1', 'field2': 'value2'}

try:
    if requests.post(url, data=data).status_code == 200:
        print("POST request successful!")
    else:
        print("Error")
except requests.exceptions.RequestException as e:
    print(f"Request Exception: {e}")

A basic example of making a POST request

Only web forms can make two kinds of requests: POST and PUT. PUT changes a specific resource on the server. To tell the server which resource to change, you need to send a request to a URI with an ID for that resource, like a blog post or a product. It doesn't matter what the resource is, but the server needs to know which one to change. You can't use a form to make a PUT request like you can with a POST. You need something like Ajax. You can use plain JavaScript or something like jQuery. If you use a framework like Angular, you can use different modules, like the HTTP module, that can make PUTs and DELETE requests.

import requests

url = 'https://example.com/update'
data = {'field1': 'new_value'}

try:
    if requests.put(url, data=data).status_code == 200:
        print("PUT request successful!")
    else:
        print("Error")
except requests.exceptions.RequestException as e:
    print(f"Request Exception: {e}")

This code demonstrates how to make a PUT. Replace 'https://example.com/update' with the actual URL where you want to update data, and adjust the data dictionary to contain the data you wish to send in the PUT request.

A DELETE request is just that: it will delete a specified resource on a server, and again, you have to let the server know what you're deleting. So you want to send an ID along with that.

import requests

url = 'https://example.com/resource/123'  # Replace with the resource URL
try:
    if requests.delete(url).status_code == 204:
        print("DELETE request successful!")
    else:
        print("Error")
except requests.exceptions.RequestException as e:
    print(f"Request Exception: {e}")

This code snippet demonstrates how to make a DELETE request. Replace 'https://example.com/resource/123' with the actual URL of the resource you want to delete, including the necessary identifier (e.g., ID).

Now, there are other types of requests, but they're very rarely used. A HEAD request is the same as GET, except it doesn't return a body in the response. It will only return the head info. OPTIONS can be used to see the supported methods of the server. And PATCH is for updating partial resources, but we're not going to get into that.

Now, let's examine a few instances of endpoints. Endpoints refer to the URI or URL where our HTTP requests are directed. The initial example pertains to an endpoint designed for a GET request, typically providing a roster of users. When requesting information about users, a comprehensive response can be obtained by sending a GET request to the API endpoint "/users/". To access specific user details, the endpoint may include additional keywords such as "details" or "show" followed by the user's ID. For instance, instead of simply using "/users/" and the ID, the endpoint could be structured as "/users/details/" or "/users/show/" with the respective ID appended. This allows for more customized and specific access to user information.

In this case, we're making a POST request to API/users, and that's going to add a user to the server or the database. Notice that this GET request and this POST request have the same endpoint, but since they're different methods, they're different requests, and that's okay.

You can use the same URL, but they have to be different requests. In this case, where we're making a PUT request to API/users/1, or you may see something like this: 'API/users/update/1,' and that's going to update that user. You'll have to send data along with that, just as you would with a POST request.

And then DELETE, you can make a DELETE request to 'API/users/1,' and that will delete that user, or you may see something like 'users/delete/1.'

If we utilize endpoints similar to the ones recently mentioned without any form of identification or verification of our identity, those become publicly accessible or open application programming interfaces (APIs). However, there are instances where authentication is required prior to utilizing them. This may involve registering your application on the provider's website, and in some cases, there may be a cost associated with it. You will need to acquire permission to access that specific data.

There are several methods through which authentication can be implemented. Typically, OAuth is employed, which entails obtaining an access token and including it in your requests. If you make a request without the appropriate access token, you will encounter an unauthorized error.

OAuth authentication can be implemented using the requests library. This example makes an HTTP GET request to a hypothetical API endpoint with the access token included:

import requests

# Replace these placeholders with your actual values
api_url = 'https://api.example.com/your-endpoint'
access_token = 'your-access-token'

# Set up the headers with the access token
headers = {
    'Authorization': f'Bearer {access_token}'
}

# Make the authenticated request
response = requests.get(api_url, headers=headers)

if response.status_code == 200:
    data = response.json()
    print(f"Success! Data: {data}")
else:
    print(f"Unauthorized Error: {response.status_code}")

Please replace 'https://api.example.com/your-endpoint' and 'your-access-token' with the actual API endpoint and access token you are working with. This code sends an HTTP GET request to the API with the access token included in the Authorization header, and it handles both successful responses and unauthorized errors.

Here are some examples of how it works with an exemplary API, which is a really nice API for beginners. It's really easy to use. How it works is you can use it without any kind of authentication, but only up to, I think it's like a hundred requests per hour. If you go over that and you didn't authorize, then you're going to get an error, and you're not going to be able to fetch the data. So there are a few different ways that this is implemented. These examples were using cURL to make our requests. cURL is just basically a tool that we can use to transfer data using multiple protocols, including HTTP.

import requests
import time

# Example API endpoint (replace with your accessible API)
api_url = 'https://api.example.com/user'

# Number of requests you want to make
num_requests = 105

for i in range(num_requests):
    response = requests.get(api_url)

    if response.status_code == 200:
        data = response.json()
        print(f"Request {i + 1}: Success! Data: {data}")
    elif response.status_code == 429:
        print(f"Request {i + 1}: Rate limit exceeded. Waiting...")
        time.sleep(3600)  # Wait for an hour before making more requests
    else:
        print(f"Request {i + 1}: Error - {response.status_code}")

# After 100 requests, you'll hit the rate limit and need to wait.

In this code, we make a series of GET requests to the example API without authentication. The code handles the scenario where the rate limit (100 requests per hour) is exceeded. If the rate limit is reached, it waits for an hour before making more requests. This simulates the behavior described in your text, where exceeding the limit without authorization results in an error. Please replace 'https://api.example.com/user' with the actual API endpoint you have access to for a practical demonstration.

  • Summary

    The article commences by defining what an API is, emphasizing its role as an intermediary between software components. Analogies, such as librarians and diplomatic ambassadors, are ingeniously employed to simplify the understanding of APIs.

The article then delves into REST, elucidating its acronym as "Representational State Transfer." It explains that REST relies predominantly on HTTP for communication and elaborates on how HTTP is fundamental for data exchange on the web. REST's ability to treat server-side objects as resources and its core operations, including GET, POST, PUT, and DELETE, are meticulously detailed.

Furthermore, the article touches upon authentication and rate limiting, providing insights into how to make authenticated requests and handle rate limits. In closing, it offers code examples for various types of requests. "Bart" is an invaluable resource for those seeking a clear and practical introduction to REST APIs.

  • Conclusion

In closing, I hope the article paints a clear and accessible picture of REST APIs, making them approachable even to newcomers. With relatable analogies and a step-by-step breakdown of REST's core principles, the article empowers readers with the knowledge they need to harness the potential of REST APIs effectively.

For both beginners and those seeking to deepen their understanding, this article stands as a valuable reference, ensuring that REST APIs are not just comprehensible but also accessible for all.