Understanding REST APIs

Illustrated graphic representing what is REST API
Published
October 4, 2021
Updated
February 13, 2024
Category

Guides

REST APIs are the most commonly used type of API on the web. Despite their ubiquity, it’s common for developers to start using them without a firm grasp of exactly what they are and how they work. 

This article explains exactly what a REST API is and examines its anatomy and features, including REST API endpoints and REST API requests and responses. Examples are provided that show you how to use a REST API to create, read, update, and delete resources.

What is a REST API?

REST (REpresentational State Transfer) is a software design pattern for APIs on the web. REST APIs are used to allow two different pieces of software to communicate with each other. If you’re writing your own software and want to integrate functionality from a third-party service — or even from another of your own services — into your code, a REST API is a standard way to do this.

You can use a REST API by making a request to a service via a REST API endpoint, which is a combination of a URL and an HTTP method. You can use different HTTP methods to create, retrieve, update, or delete some data from that service. 

REST APIs (also known as RESTful APIs) adhere to the following principles:

  • REST APIs are resource-based: Each request should either:

    • return a list of resources of the same type,

    • return a single resource, or

    • perform an action on a resource (such as create, delete, update).

  • Each URL should have a uniformity to its structure. For example, calling https://example.com/api/superhero-service/v1/superheroes/1234 might return information about Superman and https://example.com/api/superhero-service/v1/superheroes/1235 might return information about Spider-Man. The only difference is the ID but the structure is the same.

  • REST API endpoints accept HTTP methods and headers and return an HTTP status code (indicating success or the type of error).

  • They are stateless — this means each API call is independent of previous calls. So, if you had to attach an authentication header to your last call in order to log in, you’ll need to attach it again for your next call.

  • REST APIs can optionally include hypermedia, links to related API endpoints for each resource. While useful in some situations, hypermedia has not been widely adopted and most APIs don’t use this feature.

This pattern was introduced in 2000 by American computer scientist Roy Fielding in his dissertation Architectural Styles and the Design of Network-based Software Architectures with the aim of improving upon existing types of APIs such as SOAP and RPC. Since then, REST APIs have become the standard for most web applications. 

Anatomy of a REST API endpoint

You interact with REST APIs by calling an endpoint. This is a URL that is structured in a specific way for you to communicate with a particular service. There are variations in how a service structures its endpoints, but it’s normally easy to identify which parts correspond to the main elements of a REST API endpoint: the host, the service, the API version, the resource type, the resource identifier, and any parameters.

Shows the following REST API endpoint: “http://example.com/api/superhero-service/v1/superheroes/{id}?fields=name,origin” and it is labeled as follows:
“http://example.com” = the host
“/superhero-service” = the service
“/v1” = the API version
“/superheroes” = the resource type
“/{id}” = the resource identifier
“?fields=name,origin” = a parameter (called ‘fields’).

Not every endpoint will use all of these. For example, the endpoint may be part of a RESTful service that doesn’t implement separate service names for a single API, or that doesn’t include version numbers (this is common for APIs that are intended for internal use).

Host: The network location of the server hosting the RESTful service. Includes the protocol (HTTP or HTTPS).

Service: A company with multiple services will need to provide each API at a different address. In the example above, there is a superhero-service (which contains an endpoint for returning a list of superheroes, but could also contain other superhero-related endpoints — for example, one that returns a list of superhero universes, such as ”Marvel” or “DC”).

In addition to the superhero-service, the same provider might provide a princess-service  (with the endpoint http://example.com/api/princess-service/v1/princesses/ — which could return “Snow White,” “Cinderella,” etc.).

API version: API versions are used to track changes to an API. It’s normal for APIs to be regularly updated, but when there’s a breaking change, that is when a new API version (such as “v2”) needs to be specified. Users can continue to call the “v1” endpoint until they explicitly upgrade to “v2” and fix any breaking changes. 

Resource type: A resource is a series of related information. For example, a superhero resource contains a list of properties about a particular superhero, like where they’re from and what superpowers they have.

The http://example.com/api/superhero-service/v1/superheroes/ endpoint (without any resource identifier on the end) is a listing endpoint, which returns a list of superheroes, each of which contains a unique resource identifier. 

Resource identifier: The unique resource identifier is usually located at the end of an endpoint URL for retrieving information about a specific resource. For example, if Superman has the unique ID “1234,” calling http://example.com/api/superhero-service/v1/superheroes/1234 would return information about Superman. If you don’t know the correct resource identifier, you can find it by calling the listing endpoint above.

Query string parameters: You can also add query string parameters to the end of your request when requesting a list of information. These are generally used to sort or filter a list from the result. In the above example, the fields parameter is used for filtering purposes: ensuring that only certain fields about a particular superhero will be returned. In this case, only the name and origin fields are returned, and other fields are withheld.

Anatomy of a REST API request

The API endpoint is just one part of a REST API request. There are four main components to a request that you should understand when you’re writing code that needs to interact with a REST API: the endpoint, the HTTP method, the headers, and the request body.

HTTP method

All requests to a REST API endpoint include an HTTP method. The most common methods used to interact with REST API endpoints are:

  • POST creates a resource.

  • GET reads a resource.

  • PUT updates a resource.

  • DELETE deletes a resource.

For example, to read Superman’s record, you’d send an HTTP GET request to /superhero-service/v1/superheroes/1234, but to delete his record you’d send an HTTP DELETE request to exactly the same endpoint (the URL identifying the resource). The HTTP method dictates the action to be taken and the endpoint identifies the resource that the action will affect.

HTTP headers

HTTP headers are key-value pairs that are sent with an API request to give extra information to the server. Sometimes they will be automatically added to a request, but other times you will have to define them yourself. Below is an example of a Content-Type header that has been added to an API request, using cURL:

curl -H "Content-Type: application/json" https://example.com/api/

If you use Postman (a nice graphical tool for testing REST APIs), this may automatically generate some headers for you. In the example below, all headers except for the Content-Type one were automatically generated:

Screenshot from Postman showing the HTTP headers for an example request.

The most common headers to send to a REST API are:

  • Content-Type: This specifies the data format that should be returned to you. JSON is the most common option, but other examples like XML and HTML are also available.

  • Authorization: Many REST API endpoints require authorization to be able to use them. If this is the case, you’ll need to set a header with an authorization type that the REST API accepts and then add the correct authentication details. The authorization type and details on how to get an authentication token should be specified in the API documentation.

One example of an authorization header is the bearer token option. If you want to send a request to an API that requires a bearer token, you can send it in a header like this:

Screenshot from Postman showing how to add a bearer token. To do this you go to the “Authorization” tab that relates to your request, select “Bearer Token” as the “Type” and enter your authentication token in the “Token” field.

Request body

When creating or updating a resource, you need to send any new data that needs to be stored. This should be sent in the request body. You also need to tell the API the format you’re sending the data in — for example, JSON. Here’s how to use Postman to send a POST request with a JSON body that contains a new superhero, Superman, complete with different types of information that relate to him. 

Screenshot from Postman showing how to send JSON in the body of a request. To do this, go to the “Body” tab that relates to your request,  then select the “raw” radio button, followed by “JSON” in the drop-down box. Now you can paste your JSON into the window below.

Anatomy of a REST API response

A REST API response should contain:

  • An HTTP response code — such as 200 OK, 201 Created, or 404 Not Found. This allows the receiver of the response, usually a frontend or backend application, to know whether the action they attempted to take was successful (and if not, why not).

  • The requested content — this is usually in JSON format.

Example REST API JSON responses

1. GET http://example.com/api/superhero-service/v1/superheroes returns 200 OK and the following JSON:

2. POST http://example.com/api/superhero-service/v1/superheroes/ (along with data in the request body) returns 201 Created and the following JSON:

3. DELETE http://example.com/api/superhero-service/v1/superheroes/1235 (assuming this resource exists) returns 204 No Content and the following JSON:

How to create, read, update, and delete data with RESTful APIs

To fully understand how to use a REST API for creating, reading, updating, and deleting data, it helps to be able to follow through some concrete examples. We will use the Contentful API to walk you through some examples, step by step. If you want to follow along, you can sign up to Contentful for free.

Once you’ve created a Contentful account and logged in, you’ll automatically be inside a space, which is a workspace that you can fill with all of the content you want to publish to your websites and apps.

 Screenshot of the first page you see when you log into the Contentful app.

To start interacting with the Contentful REST API, you’ll need an access token for authentication purposes. To get your access token, go to “Settings” → “CMA tokens,” and then click “Create personal access token.” Give your token a name, make a note of it, and click the “Generate” button. Now copy your access token and save it somewhere safe.

Screenshot of the “Create personal access token” box with the “Generate” button highlighted.

We’re now going to check if your API key is working. We recommend using Postman for this. You need to make a GET request to https://api.contentful.com/spaces and pass in a “Bearer Token” authorization header with your CMA token, as we covered earlier.

Screenshot showing how to add a Bearer Token in Postman. The “Authorization” tab is selected and the “Type” drop down box has “Bearer Token” selected.

This will return a 200 OK and some JSON. If you scroll through the JSON you should be able to find the ID of your space. Copy it and save it somewhere as you’ll need it in the next step. 

Screenshot from Postman showing the returned JSON with the ID field highlighted.

Reading a list of resources with HTTP GET

To demonstrate how to use the Contentful REST API, we’re going to practice reading, creating, updating, and deleting some environments.

In Contentful, environments are a way to maintain multiple versions of your content. Every account starts with one default environment called master, but very soon you’ll want to create other environments like a sandbox environment for testing out some new content that you wish to work on without affecting the master environment. 

To read a list of environments from Contentful, send a GET request to: 

https://api.contentful.com/spaces/{space_id}/environments

Replace {space_id} with the ID of your space, which you saved from earlier, and attach the following HTTP headers:

Authorization: Bearer <CMA_TOKEN>

Replace <CMA_TOKEN> with your actual CMA token.

This will return some JSON that contains a list of environments and related information, along with an HTTP 200 OK status code.

Creating a new resource with HTTP POST

To create a new environment resource in Contentful, send an HTTP POST request to:

https://api.contentful.com/spaces/{space_id}/environments

Replace {space_id} with the ID of your space, which you saved from earlier, and attach the following HTTP headers:

Authorization: Bearer <CMA_TOKEN>

Content-Type: application/vnd.contentful.management.v1+json

Add the name of the environment you wish to create in the body of the request:

body: {

  "name": "My environment name"

}

This will create a new environment in the Contentful app, which you will be able to see either by logging in using your browser, or by calling the “list environment” endpoint for your space:

GET https://api.contentful.com/spaces/{space_id}/environments

When you use HTTP POST to create a resource in Contentful, it will have an auto-generated ID, or you can specify one yourself by using the HTTP PUT method to create a resource.

Updating a resource with HTTP PUT

We will use an HTTP PUT request to update an environment in Contentful by changing its name. To do this, send an HTTP PUT request to the following URL, where {environment_id} is the ID of the environment with the name you wish to change and {space_id} is the ID of your space.

https://api.contentful.com/spaces/{space_id}/environments/{environment_id}

Use the following HTTP headers:

Authorization: Bearer <CMA_TOKEN>

Content-Type: application/vnd.contentful.management.v1+json

And send the name of the environment you wish to create in the body of the request:

body: {

  "name": "My new environment name"

}

Finally, you’ll need to specify which version of the environment you’re updating, by adding the following header, and replacing <existing_version> with the correct version:

X-Contentful-Version: <existing_version>

You should know that this is something specific to Contentful’s REST API and you may not need to do the same thing when doing updates with other REST APIs. However, many REST APIs have added extra features that will be similar to this, and you’ll discover this when reading their API documentation. 

If you’re not sure what the most recent version is, you can find out by sending a GET request to the same endpoint, and the response will let you know.

Screenshot from Postman showing a GET request to an endpoint with some JSON as the response, with the version number highlighted.

Deleting a resource with HTTP DELETE

To delete a particular environment within a space in Contentful, send an HTTP DELETE request to the following URL, where {space_id} is the ID of your space and {environment_id} is the ID of the environment you wish to delete:

https://api.contentful.com/spaces/{space_id}/environments/{environment_id}

And use the following HTTP header:

Authorization: Bearer <CMA_TOKEN>

REST APIs in summary

An API is a way to communicate between different software services using programming languages such as JavaScript, PHP, Python, Java, Ruby, and C#. REST is a set of rules and guidelines for creating a particular type of API, and not all APIs are RESTful APIs. 

REST stands for Representational State Transfer. RESTful APIs:

  • Are based on resources.

  • Are uniform in structure.

  • Accept HTTP methods and headers, and return HTTP status codes as a response.

  • Are stateless.

  • Can contain hypermedia.

Explore the Contentful API documentation to solidify your understanding of REST APIs.

Frequently asked questions

What is meant by REST API?

A REST APIs is an API that follows REST (REpresentational State Transfer) principles, making it easy for systems to communicate with each other. RESTful systems have separation of concerns between client and server, which means each system can be implemented independently of one another. REST APIs are stateless, meaning that each API request is completely independent from any previous requests. 

How do REST APIs work?

REST APIs expose endpoints to a client, allowing them to make calls to the server. The client sends an HTTP request to an endpoint, and the server receives the request. 

In most cases, some authentication details are sent with the request, and the server deals with checking that the client is allowed to make their request. As RESTful systems are stateless, a client needs to be re-authenticated with every single request. 

The server then processes the request and returns a response, usually in JSON or a similar format. It also returns an HTTP status code to inform the user of success or failure.

Why are REST APIs used?

RESTful services allow separation of concerns between client and server, and between different parts of the server.

REST APIs are easy to use — they use HTTP calls, which is the language of the web. Developers are already familiar with this.

REST APIs are also scalable, for two reasons:

  • All GET, PUT, and DELETE calls can be cached (because they’re idempotent). 

  • Servers run faster, as they don’t have to store state (REST is stateless).

Start building

Use your favorite tech stack, language, and framework of your choice.

About the authors

Don't miss the latest

Get updates in your inbox
Discover new insights from the Contentful developer community each month.
add-circle arrow-right remove style-two-pin-marker subtract-circle remove