DEV Community

Juan Cruz Martinez
Juan Cruz Martinez

Posted on • Originally published at livecodestream.dev on

What is a REST API?

Live Code Stream

The modern web highly depends on the interconnectivity of systems. Long past are the times when a website would simply query a DB and show that information to the user in one single step. The web applications we interact with today can’t gather all the information they need from a single place or a single call to render everything that happens in the UI.

For example, if you visit amazon.com, you’ll first receive a response from the server with a basic UI and some spinners indicating something is still loading. Once the information is loaded and available, you’ll start seeing different sections like your recommended items, customers like you bought, promotions, ads, etc.

Each of these sections retrieves the information from a different place. At the same time, each of these calls to an Amazon server would travel through multiple other services to check for offers, availability, delivery times, etc.


What Is an API?

API for interconnected systems
API for interconnected systems

Navigating a world of interconnected systems is possible thanks to APIs (Application Programming Interfaces) and all the tools developed around them. You can think of an API as a set of rules that applications must follow to talk to each other, so when one app wants to get data from another, it does so by following the rules of that API. This means we don’t have to write our communication protocols, as APIs would do the heavy lifting as long as we stick to the rules.

APIs have been around for decades now; it’s just that with the rise of cloud computing and web technologies, we’ve seen a massive boost in their usage. Many tools are available that allow us to quickly set up APIs that talk to databases, services, remote servers, etc.

One particular type of API is REST API, which is the most dominant API type for the web, and it is what we will focus on in this article.


What Is a REST API?

REST stands for Representational State Transfer (I know, the name doesn’t mean much), and it is an architectural pattern that defines how web applications should interact with each other. A REST API follows these constraints to make sure the communication between two systems is consistent and predictable:

  • Client-server architecture : The client requests the server responsible for responding to those requests and providing the requested resources. So far, it’s pretty similar to how a browser would work.
  • Stateless communication : Each client request should have all the information needed by the server to process it and respond accordingly. The server shouldn’t need to remember anything related to a previous request.
  • Cacheability : The server should indicate whether a response can be cached, meaning that the same request can return the same response as long as it hasn’t changed.
  • Layered system : Each application layer should only interact with its own layers and doesn’t need to know anything about the inner workings of other elements in the system architecture. For example, a REST API doesn’t need to know if it interacts with a browser, another API, a server, or anything else.
  • Code on demand (optional): This is an optional constraint that states that the server can send executable code to the client as part of a response. This code would run on the client and might modify how it responds to subsequent requests.
  • Uniform interface : The requests and responses should be uniform, which ensures that the client can understand and interact with the server. We’ll learn more about this later on.

What Is Meant by RESTful API?

There is no universal definition of a RESTful API, but it usually refers to an API that follows the constraints of the REST architectural pattern. It can also describe an architecture or design style for building APIs and web services.

RESTful APIs typically divide into two main categories:

  1. The first category is data-oriented and is usually used for retrieving and changing data from a server. This type of API typically uses HTTP methods like GET, POST, PUT, and DELETE to manipulate data.

  2. The second category is action-oriented and defines an interface for actions like playing a song, sending a message, or launching an application. This type of API typically uses HTTP methods like POST, PATCH, and PUT.


What Are the Benefits of RESTful APIs?

RESTful APIs are widely used for their scalability, simplicity, and flexibility. They provide a consistent way of interacting with web services, which makes them easier to use and maintain. Some of the benefits include:

  • Scalability : Can easily scale up or down to respond to increasing or decreasing demand from connected clients.
  • Flexibility : Support 100% client-server separation. For a RESTful API, it doesn’t matter if the client is a web browser, a server, another API, or an IoT device. The answer for the same request will be the same regardless.
  • Consistency : Use a uniform interface, making them easier to understand and use.
  • Ease of development : These are much simpler to develop than other services. The ability to layer application functions makes it easier to introduce critical changes, such as migrating database engines or other critical components. This heavily depends on how you structure your RESTful APIs for your product or organization.

How Do RESTful APIs Work?

RESTful APIs are no different than websites in a way. A client initiates a request to the API when it requires information or wants to change a resource. Then the API would respond to how it went and what the result was.

Depending on the RESTful API, things can be a bit different, but generally speaking, here are the steps:

  1. The client initiates a request to the server. The request must follow the API specifications to ensure the server understands such a request. Such specifications are generally present in the API documentation.
  2. The server authenticates the client and validates that the client is authorized to make such a request.
  3. The server processes the request.
  4. The server returns a response to the client. The response contains information representing if the processing was successful or not. It may also include any information requested by the client formatted according to the API specifications (most commonly using JSON or XML).

RESTful API Requests

Example of an API request with components
Example of an API request with components

A RESTful API client request requires the following components to work:

URI (Unique resource identifier)

More commonly known as an API endpoint, a URI is a unique identifier that identifies the required resource. For RESTful web services, the URI is related to the Uniform resource locator (URL). For example, https://example.com/api/user will represent the user resource in an API.

METHOD

The most common RESTful APIs are RESTful web APIs (or RESTful web services) which work by using the Hypertext Transfer Protocol (HTTP). An HTTP method tells the server what it needs to do to the resource. The following are five common methods:

  • GET : Retrieve a resource from the server.
  • POST : Create a new resource.
  • PUT : Update an existing resource.
  • PATCH : Partially update an existing resource.
  • DELETE : Delete an existing resource.

HTTP headers

HTTP headers are metadata exchanged between the client and the web server. It can contain data from the client, e.g., the user agent. Data from the request, e.g., authentication or the format for the response. And data from the response, such as the request status and more.

Data / Body data

Also known as a payload, the data is often in JSON (JavaScript object notation) or XML format. The data contains all of the information that needs to be processed by the server, and it may be required for some HTTP methods such as PUT, PATCH, POST, etc.

Parameters

RESTful API requests can include parameters that give the server more details about what needs to be done.

  • Query parameters let you filter, sort, and limit the data requested by the client. E.g., https://example.com/api/users?sort_by=name will respond with all users sorted by name.
  • Path parameters specify URL details, such as identifying a specific resource by its unique identifier (ID). E.g., https://example.com/api/user/123 will request information about the user with ID 123.
  • Cookie parameters for authenticating clients

RESTful API Responses

Example of an API response with components
Example of an API response with components

A RESTful API response requires the following components to work:

HTTP status code

The HTTP status code is an essential part of an API response. It tells the client if the request was successful and what action needs to be taken next. For instance, a status code of 2xx indicates that the request was processed successfully, while 4xx or 5xx would suggest something went wrong.

Other status codes like 3xx indicate a URL redirection.

Here are some commonly found status codes in actual REST APIs:

  • 200: Generic success response.
  • 201: Created.
  • 400: Incorrect request that the server cannot process.
  • 404: Resource not found.
  • 500: Internal server error.
  • 503: Service unavailable.

Body

The response body is the main content of an API response. Depending on the request, it may contain a representation of the requested resource or an error message. The format for this response can be set by the requesting client but is usually in JSON or XML format. Many APIs though would only provide only one format, so always check with their documentation which options are available.

For example, if the client requests information about a user using by accessing the following endpoint: https://example.com/api/user/123, it may receive a response like: {"id":123, "name": "Juan"}.

Headers

Headers are used to provide more information about the response. It includes details such as the content type, language, caching instructions, etc.

No doubt that the most important header for a client may be the “HTTP Status code” we already talked about, but there are other headers. For example, a response from an API may return a Content-Type header with the value application/json, indicating that it is sending back data in JSON format.


Playing with a Demo RESTful API

By now, you should better understand RESTful APIs and how they works. If you want to learn more about making requests and responses, the best way is by playing with an example API.

There are many free APIs available on the web that let you send requests and get responses from their servers. One such demo web API is Reqres, which we will be using in our demo.

We’ll explore Reqres by working with the user resource. So first, let’s list all the users.

NOTE: we’ll use curl to query the web API; if you prefer another client, follow along with the URLs and the data that we provide to the API.

curl -i https://reqres.in/api/user

Enter fullscreen mode Exit fullscreen mode

If you run that, curl will print all the response headers plus the response body on the screen, and you’ll see something like this:

HTTP/2 200
date: Sun, 08 Jan 2023 23:07:49 GMT
content-type: application/json; charset=utf-8
content-length: 705
x-powered-by: Express
access-control-allow-origin: *
etag: W/"2c1-N6Rqerxquq2kgQhL51EiSg4x0R8"
via: 1.1 vegur
cache-control: max-age=14400
cf-cache-status: HIT
age: 101
accept-ranges: bytes
report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=rf0iP0dVU62j%2BjsTlakFpwkRofhD2d904yCmqXq%2F98JXRS%2F174nqlwYakBOymZgfB%2FClEEH%2B0n%2BjEDepgl3Ks1%2B4KxtlnQx31DQCUHhxQyttQSUTPlNJYilUw7rAa6njeY%2F1c2twzw%3D%3D"}],"group":"cf-nel","max_age":604800}
nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
server: cloudflare
cf-ray: 786897748e211e65-MUC

{"page":1,"per_page":6,"total":12,"total_pages":2,"data":[{"id":1,"name":"cerulean","year":2000,"color":"#98B2D1","pantone_value":"15-4020"},{"id":2,"name":"fuchsia rose","year":2001,"color":"#C74375","pantone_value":"17-2031"},{"id":3,"name":"true red","year":2002,"color":"#BF1932","pantone_value":"19-1664"},{"id":4,"name":"aqua sky","year":2003,"color":"#7BC4C4","pantone_value":"14-4811"},{"id":5,"name":"tigerlily","year":2004,"color":"#E2583E","pantone_value":"17-1456"},{"id":6,"name":"blue turquoise","year":2005,"color":"#53B0AE","pantone_value":"15-5217"}],"support":{"url":"https://reqres.in/#support-heading","text":"To keep ReqRes free, contributions towards server costs are appreciated!"}}% 

Enter fullscreen mode Exit fullscreen mode

We need to read from here the HTTP status code at the beginning (200) and the response data, which is the long JSON file. This indicates that all went well, and we got our response data.

Now, to query a single user, the user with id=1, you can run:

curl -i https://reqres.in/api/user/1

Enter fullscreen mode Exit fullscreen mode

I won’t be showing all responses here as they are very long, but you can follow up with your terminal.

We can also try to query an invalid user.

curl -i https://reqres.in/api/user/not-found

Enter fullscreen mode Exit fullscreen mode

And if you look at the response, now the response body is an empty JSON object, and the HTTP status code is 404 (not found).

To create a user, we can send a POST request with the user information as JSON:

curl -i -X POST https://reqres.in/api/user -d '{"name": "jc","job": "author"}'

Enter fullscreen mode Exit fullscreen mode

Now the response would be a 201 (Created), and if you list the users again on the last page, you’ll see the newly created user.


Securing a RESTful Web Service from Unauthorized Access

We’ve seen that RESTful APIs provide a powerful way to access and manipulate data on the server side. But it is also essential to ensure that your API is secure so only users with proper permissions can access the data.

Before we continue, we need to make an essential distinction between authentication and authorization. Authentication is the process of verifying a user’s identity, while authorization is the process of validating what that user can do.

For example, users might be authenticated with their username and password but not authorized to delete a post or access another resource.

There are four standard methods to implement REST API authentication for web (HTTP) APIs:

Basic authentication

This is based on a username and password sent in plain text (base64) as part of the HTTP request headers.

Bearer token

This is a server-generated token sent in the request header. The client will use this token to authenticate with the server on subsequent requests without sending their username or password each time. The bearer token is typically an encrypted string of characters and may have some methods to validate that a token is valid. The most popular option is JWT.

API key

An API key is a unique identifier generated by the server that can be used to access specific resources. This method is less secure as keys are typically long-lived (if not without expiration) and are commonly transferred as query parameters.

OAuth

OAuth is an open standard for authorization that provides a secure way to access APIs by allowing users to approve access with their usernames and password without sharing them. This method relies on third-party providers (like Google or Facebook) to authenticate users.


The Problems with REST APIs

REST APIs can be the foundation of a powerful application, but they also bring some complications and potential security risks. Here are some of the most common issues:

  • Insecure endpoints : Without proper authentication, endpoints may be exposed to unauthorized access.
  • Inconsistent API design : If an API is poorly designed, it may be difficult to use and maintain.
  • Unclear error messages : Without proper documentation, developers may not understand why an API call failed or how to fix the issue.
  • Lack of versioning : APIs should be versioned to keep them up-to-date with changes in technology and standards.
  • Poor performance : If an API is slow to respond, it can cause significant delays in an application.

These issues can be addressed by following industry standards and best practices when building your REST API. It’s important to plan ahead to ensure that your API is secure, efficient, and easy to use.


Developer Tools to Work with APIs

There are many tools available to help developers work with APIs. Here are a few of the most popular options:

  • Postman: A powerful suite of tools that can be used to test and debug APIs.
  • cURL: An open-source command-line tool used to send HTTP requests.
  • Insomnia: A cross-platform application designed to simplify API testing and debugging.
  • Swagger: A powerful set of tools designed to help create, document, and test APIs.

RESTful API Examples

There are also a number of REST APIs publicly available as sandboxes for users to build demo applications or to learn more about APIs.

Here are a few of my favorites:

  • Reqres: A free public API for testing and prototyping.
  • JSONPlaceholder: A fake online REST API for developers to practice with.
  • Public APIs: A massive directory of open-source, publicly available APIs.
  • Fun API List: A list of fun and interesting APIs to explore.

If you want to build your own, I recommend you get started with a RESTful API tutorial. Here are some recommendations for some popular programming languages:


Conclusion

REST APIs are an essential part of web application development. They provide a standard way for developers to access and manipulate data, making it easier to create powerful applications. With the right tools and best practices, you can create secure, reliable APIs quickly and efficiently. With so many public APIs available, there is no excuse not to explore new possibilities and create something amazing.

So what are you waiting for? Start building APIs!

Subscribe to my weekly newsletter for developers and builders and get a weekly email with relevant content.

Top comments (0)