At some point in your career as a developer, you’ve likely encountered RESTful APIs. But, do you know what they are? How do they work?
In this guide, we discuss the essentials of REST APIs, covering everything you need to know to query a REST API.
What is a RESTful API?
RESTful APIs allow you to retrieve data. For example, you can use a REST API to retrieve data about your favorite movies from a movie API, or your fitness data from the Fitbit API.
API stands for “Application Programming Interface.” It is a program that allows websites and servers to talk to each other. An API is hosted on a server with its own database; websites and programs can retrieve data from the API.
REST, which stands for “REpresentational State Transfer,” is a set of guidelines determining how a web API should be structured.
REST Request Example
To work with an API using the REST architectural style, you need to make a request. The data that you receive after you make a request is called the response.
Let’s start by discussing endpoints. When you’re making a request, you need to query an endpoint. This is the URL from which you want to get data.
Suppose you want to retrieve data from the Hacker News API. This API allows us to retrieve data on posts from the Y Combinator Hacker News platform.
To make your request, you need to read through the API documentation. In this case, the Hacker News API says that we can use the following URL to retrieve a story:
https://hacker-news.firebaseio.com/v0/item/:postid.json?print=prettyIn this example, :postid is the post that we want to retrieve. Generally speaking, when you see colons in API documentation, you should insert a variable. In this case, suppose we want to get the post with the ID 23460066. We could do so using this URL:
https://hacker-news.firebaseio.com/v0/item/23460066.json?print=prettyNow that we have a REST request ready, we can make our request to the API.
Making a REST Request
Most programming languages have their own modules to allow web requests. Python offers the Python requests package. JavaScript offers the Fetch API and isomorphic-fetch. For this tutorial, we’re going to use a command line program called cURL. This allows you to make web requests from your command line.
To make a request, all we have to do is use the curl command, followed by the REST URL that we want to query. In the example of the Hacker News API above, we’d use the following command:
curl https://hacker-news.firebaseio.com/v0/item/23460066.json?print=pretty
Our code returns:
As you can see, the API has returned the data for the post with the ID 23460066. We can see the post’s author, comment “kids,” title, and more. If we want to get another post, all we have to do is change the post ID.
The data returned by a request is usually structured in the JSON format. JSON stands for JavaScript Notation, and is a standard way of expressing data.
In JSON data, keys are stored on the left-hand side of a colon. The key is the label that is assigned to a value. Values are stored on the right-hand side of a colon. Here’s an example key-value pair from the above response:
"by": "arkadiyt"
The key in this case is “by” and the value is “arkadiyt”. These values are separated with a colon.
How do REST Requests Work?
There are four parts to a REST request:
- An endpoint URL
- A HTTP method
- Body (data)
- HTTP headers
An endpoint is the URL that you query when making a REST request. In the example above, we queried a URL on the Hacker News API, which allowed us to get data about a certain post.
Let’s discuss the other parts of a REST request.
HTTP Method
HTTP offers several methods to interact with a REST API. These methods allow you to create, read, update, and delete (CRUD) data on an API.
The four main types of requests you’ll encounter are the following:
- GET: This request allows you to retrieve data from a server.
- POST: This allows you to create new data on a server.
- PUT: Allows you to update a record on a server.
- DELETE: This allows you to delete information on a server.
To specify the method used with an API request, you can use the -X flag in curl. Here’s an example of a command that allows you to run a POST request on an API:
curl -X POST https://yourapihere.com/api_endpoint
Body
The body of your request (also known as the data) is the information that you want to send to a server. You can only specify a request body with a POST, PUT or DELETE request.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
You can use the -d flag to send data using cURL. To do so, you should specify the property name of the data you want to send followed by an equals sign and the value of that property name. Here’s an example of a cURL request that sends data to a server:
curl -X POST [URL] -d propertyName=value
HTTP Headers
Response headers provide additional information to a client and a server. These headers are often used to specify the type of content being sent to an API, or the authentication credentials you’ll use to sign in to an API. HTTP headers are structured as follows:
"Authentication: Bearer your_token"
On the left side of the colon, you should specify the name of the property you want to set. In this case, we are setting a property for the attribute “Authentication.” On the right side of the colon, you should specify the value of the attribute you have set.
Here’s an example of a cURL request with a header attached:
curl -X POST -H "Authentication: Bearer your_token" [URL]
This request will send the header “Authentication: Bearer your_token” to the API URL that we specify.
Authentication with REST
Before you start working with REST APIs, you need to know about authentication. Authentication ensures that only you can access data associated with your account.
Most POST, PATCH and DELETE requests will require an authentication key. This is because they allow you to modify data on a server. You may also be asked to specify an authentication key with a GET request if you are accessing non-public information.
In our Hacker News example from earlier, we didn’t need to specify any authentication credentials because the Hacker News API is publicly available. However, if we need to, there are several ways to authenticate ourselves using an API:
- Basic authentication: This involves specifying a user’s username and password to authenticate with an API.
- OAuth: OAuth is a protocol for authentication that can be sent with each API request to authenticate a user, until the OAuth key expires.
- API keys: API keys give you specific access rights when querying an API. These keys will be associated with your account on a web service.
The way in which you query an API depends on what method of authentication you are using. Usually, you’ll find instructions on how to authenticate with an API in the API’s documentation.
Suppose we want to query the Airtable API. To do so, we need an authentication key. We can retrieve this by following the instructions from the Airtable API documentation.
Here’s an example request that allows me to retrieve records in an Airtable base following the API documentation:
curl https://api.airtable.com/v0/appiTz7oLBs9hDIFg/Tracker -H "Authorization: Bearer YOUR_API_KEY"
When I run this query with my private API key in place of “YOUR_API_KEY,” the following response is returned:
{ "records": [ { "id": "rec3fxfwVYvORk2E5", "fields": { "Drink": "Black Decaf Tea", "Date": "2020-05-30T14:04:22.000Z" }, "createdTime": "2020-05-30T14:04:22.000Z" } ] }
As you can see, the API has returned a record from my database. But, if I hadn’t specified an authorization header, the following would have been returned:
{"error":{"type":"AUTHENTICATION_REQUIRED","message":"Authentication required"}}
HTTP Error Messages
When interacting with an API, you may encounter a few different error messages. These may appear for different reasons. For example, you may have specified the wrong authentication key, or you may be making a HTTP request to an endpoint that does not exist.
Here are the main codes you can expect to see in your response to an API:
- 2xx means a request has succeeded
- 3xx means a request has been redirected
- 4xx means a client-side error has occurred
- 5xx means a server-side error has been returned
We can see these codes by specifying the -I flag, which allows us to see the HTTP status code sent by a request. Suppose we tried to query the Airtable API without an API key. We could do so using this command:
curl https://api.airtable.com/v0/appiTz7oLBs9hDIFg/Tracker -I
When we run this command, the following is returned:
HTTP/1.1 401 Unauthorized Content-Type: application/json; charset=utf-8 Date: Tue, 09 Jun 2020 08:26:32 GMT ETag: W/"50-8xYAvLBWleFLl/buYhG+M42uVZo" …
As you can see, a 401 request was returned. This is because we didn’t specify a valid API key.
Your Next Steps
REST APIs are a useful tool to interact with RESTful web services. REST principles are the structure used to make a web request to an API.
If you’re looking to get started working with a REST API, a few tools can help you, including:
- Postman: A tool to help you test REST APIs
- Insomnia: Allows you to explore and test GraphQL and REST APIs
- Swagger: A range of tools to assist with REST API design and testing.
In this article, we used two APIs: the Hacker News API and the Airtable API. But there are many others you can play around with.
Many of the web services you interact with on a daily basis have an API. Twitter, Spotify, GitHub, and CircleCI all have APIs that you can use. There’s also a great list of public APIs that you can use for free in the “public-apis” repository on GitHub.
The best way to enhance your understanding of REST APIs is to work with them. Pick an API that interests you and make a few requests!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.