REST APIs

last updated: March 18, 2024

Overview

If you're new to the idea of REST APIs, you may find the concept a bit intimidating -- maybe you're not quite sure where to even start getting started. If this sounds familiar, then good news! You're not alone.

In this guide, you'll learn some common API-related terms, and get a general introduction to how data can be transmitted online. After that we'll practice using a real API to send and receive data to and from a remote internet server (no programming necessary!). By the end of the lesson, you will be equipped to begin using other APIs - including Planet's API - in real-world situations.

What are we talking about?

First thing's first: let's demystify some of the jargon that you'll likely encounter when talking about, or working with, web APIs:

  • An API, or Application Programming Interface, defines a way of communicating between software applications.

  • REST stands for Representational State Transfer, and is an architectural style of creating web services that communicate with web resources.

  • JSON stands for JavaScript Object Notation, and is a standard text-based format that’s used to represent structured data.

If those definitions seem a bit opaque, don't worry! For the most part these are broad concepts that software developers use to inform the work they do. As an API user, as long as you have a general familiarity with the terms, you are good to go.

A note about names: when talking about web services that allow us to access resources over the web, we commonly say REST (or RESTful) API. In many cases, however, you may simply hear API used to refer to a REST API. You may have noticed that here in this guide, we're also using the phrase web API interchangably with those terms. Any of the above is acceptable, and will be understood just fine in the context of "working with data services over the web".

How does the web work?

Before we continue learning about web APIs, take a moment to ask yourself: What happens when I type 'www.google.com' and hit enter in my browser?

In order to better understand how communication over the web works, let's break down what goes on behind-the-scenes when you access a website in your browser:

URL → IP Address
When you enter a URL like www.google.com, that URL is translated into an IP address: a unique address representing a destination on the internet.
Browser requests information from that IP
Once your browser knows the destination for the URL you typed, it makes a request to that destination.
Server at IP responds to the request
The IP address our URL translated into leads to a web server: when this server receives an incoming request, it parses that request & generates a response. The response is then sent from the server, back to your browser.
Browser renders the response
Once your browser receives the response to its original request, it will attempt to render the result in your browser window: e.g., displaying images, drawing clickable buttons, setting font sizes and colors, etc.

You view the result! :

What is JSON?

JSON stands for JavaScript Object Notation, and is a standard text-based format that’s used to represent structured data. JSON is based on, and resembles, JavaScript object formatting. Even though it is based on JavaScript, JSON works independently of JavaScript and many different programming languages are capable of reading JSON. Let’s break this down in case you’re not familiar with JavaScript objects.

{
    "nameOfThisGroup": "Dog Squad",
    "whereAreThey": "In the dog house",
    "whenFormed": 2020,
    "darkSecret": "Leader is a cat",
    "active": true,
    "members": [
        {
            "name": "Atlas the Active",
            "age": 2,
            "species": "Dog",
            "breed": "Australian Kelpie",
            "powers": [
                "Leaving it",
                "Infiltrating locked spaces",
                "Time travel"
            ]
        },
        {
            "name": "Athena the Great",
            "age": 9,
            "species": "Dog",
            "breed": "Newfoundland",
            "powers": [
                "Radioactive drool",
                "Stashing the goods",
                "Teleportation"
            ]
        },
        {
            "name": "Lilith",
            "age": 5000,
            "species": "Cat",
            "breed": "Short-haired",
            "powers": [
                "Immortality",
                "Flight",
                "X-ray vision"
            ]
        },
        {
            "name": "Merlin",
            "age": 3,
            "species": "Cat",
            "breed": "Tabby",
            "powers": [
                "Sleep of the dead",
                "Master of the chase",
                "Invisibility"
            ]
        }
    ]
}

If you take a look at the above example, you’ll see that objects are essentially standard data types arranged in a way that is easily readable for many programming languages. The data is typically arranged in a parent child, or nested, format, creating a data hierarchy. At the beginning you see the information about the group as a whole (the parent), in this case, a squad of super hero house pets, and below that are the members of the group (the children) and their individual information.

As you can see, each member has the same list of data, with their individual values given after the assigned data. The data types used include strings (or lists of characters), numbers, arrays, and booleans (true or false)

If you’d like to further explore JSON, there are many great resources available. Check out JSON Lint: JSON Online Validator and Formatter, JSON.org, Working with JSON - Learn web development | MDN, and JSON and APIs with Python.

Requests & Responses

When we communicate over the web, HTTP, or HyperText Transfer Protocol, is the 'language' that clients like our web browser use to communicate with web servers. HTTP defines a standardized way of communicating information through a series of requests and responses.

A client makes a request, using HTTP, to a server. In return, the server will send a response back to the client.

Headers & Bodies

Both requests and responses have two parts: a header, and (optionally) a body. Request allow the client to send information about the request to the server. Similarly, response headers contain information about the response. We'll learn more about what kind of meta-information headers can contain later in this tutorial.

In both requests & responses, the body contains the actual data being transmitted: for example, in a weather API that returns temperatures at a given location, the temperature data would be returned in the response body.

Request Methods

In REST APIs, every request has an HTTP method type associated with it: this method is used to signal the type of action the request wishes to perform.

The most common HTTP methods include:

GET
A GET request asks to receive a copy of a resource
POST
A POST request sends data to a server in order to create a new resource
PUT
A PUT request sends data to a server in order to modify an existing resource
DELETE
A DELETE request is - as you might imagine - sent to delete a resource

When working with REST APIs, we often talk about requests by method type; e.g., we might "make a GET request" or "POST to the API".

Response Codes

HTTP responses don't have methods, but they do have status codes: HTTP status codes are included in the header of every response in a REST API.

Status codes include information about the result of the original request: if all goes well, for example, the 200 - OK status code is returned.

You may be familiar with some of the more common HTTP status codes, such as:

404 - Not Found
The requested resource was not found
401 - Unauthorized
Your request is not authorized to be completed
500 - Internal Server Error
Something went wrong while the server was processing your request

You can read more about these and other HTTP status codes at httpstatuses.com.

URLs

In REST APIs, resources are located at Uniform Resource Locators (URLs).

URLs can include paths: http://example.com/path/to/resource

Here, the nested path path/to indicates the resource resource's location, for example within a directory on the remote server's file system.

URLs can also include query strings: http://example.com/path/to/resource?name=cat&color=black

Here, the ? at the end of the path indicates the beginning of a query string: in this example, the query string is name=cat&color=black. Query strings can be used to query a resource based on given fields (like "name" and "color" here) and values (like "cat" and "black").

Authentication & Authorization

Most REST APIs require you to be authenticated in order to use them. Authentication allows the API service to connect a request to a specific user. An authenticated user has successfully identified themselves to the API when making their request.

There are many different ways of providing authentication when making an API request. Some of the more common include using a username & password, or sending an API key as part of the request. To use the Planet API, for example, you create a user account, which then gives you access to a unique API key.

Authentication is not to be confused with Authorization: a REST API may restrict some resources based on level of authorized access. For example, one authenticated user may be authorized to request an existing resource, but may not be authorized to delete a resource.

Common tools for all platforms: curl, Postman

There are a number of tools that make it easier to interact with APIs. Two common ones, that are available for most platforms, are curl and Postman. If you're comfortable with the command line, curl is a great command-line tool that is already installed on most modern operating systems. If you're looking for either something with a graphical interface, or perhaps more feature-ful than curl, then Postman is also a great tool to add to your toolbox.

To check if curl is installed on your computer, open a terminal/command prompt (Windows users: open Powershell), and at the prompt type:

curl --help

If you get a long result showing command usage information, curl is installed and ready to use. If, however, you see "command not found" -- then use the Download Wizard here to download the curl executable for your operating system.

To use Postman, you can either install it as a Chrome browser extension, or as a standalone native application. You can find the Chrome extension here, or get the native application from here.

The remaining API examples in this tutorial will use curl, but you are welcome to use any tool you prefer to follow along.

Putting it all together

Finally! At this point we've talked a bit about how the web works, and how REST APIs function as a way of requesting & receiving data. Now let's put what we've learned into practice and use a real API: we'll use The Cat API, an API that responds to requests for images of cats with a random image result.

We'll start by making a GET request. Type the following curl command at a command prompt:

curl -v GET https://api.thecatapi.com/v1/images/search

A closer look at that line, broken down into separate parts:

Here we're making a GET request to an API. We've used the optional -v flag for curl in order to have the command print verbose output.

Now let's take a closer look at what that command does:

When you make a request using curl, the first thing you see is the IP address the target URL resolves to (in this case, 23.217.138.110) followed by your request's headers.

Following our request headers comes the response header section: here, we see that the server returned a 200 status code, followed by the date & time the response was sent. The next few lines encode additional information about the response.

Finally, we see the response body: in this case, the body itself is a block of JSON-formatted text content. If you read this JSON response, you'll notice an image URL value encoded within. Copy that URL to your browser & view the result:

https://cdn2.thecatapi.com/images/MTk2NzgzNw.jpg

Congratulations, you've successfully requested an image of a cat from the Cat API!

Even more API practice

Let's create a slightly more complex query string by chaining multiple queries together. Also, now that we're familiar with headers, we can drop the -v verbose flag so that curl only outputs the response body:

curl -X GET "https://api.thecatapi.com/v1/images/search?category_ids=1"

Here we're requesting a JSON-formatted response returning only images that are JPEGs of cats in the category "hats".

The Cat API has a number of image categories (like "hats"), with number ids assigned to each category: as an exercise, use the API docs here to learn how to make an API request that returns the complete list of categories.

We can even practice using an API key for authentication with The Cat API. To get your own API key, you'll need to request one from here. Once your key has been emailed to you, replace the dummy key "12345" in the example below with your own:

curl -X GET "https://api.thecatapi.com/v1/images/search?category_ids=1&api_key=12345"

REST APIs for developers

While curl is a useful tool for authenticating requests quickly, its utility is confined to to the command line. Perhaps a user wants to build a web app showing only the cutest of kitties. They would have to integrate the Cat API into the backend of their application. Below is a practical example of a Python request to my favorite API:

import requests
# install the requests library to make a get request

BASE_URL = 'https://api.thecatapi.com/v1/images/search'

headers = {
    'x-api-key': '12345'
}
# authenticate request by sending api key in headers as specified in the cat api documentation

kitties = requests.get(BASE_URL, headers=headers)

print(kitties)
# prints the (hopefully 200) response for kitties

Where to go from here

Now that you've made a few requests against The Cat API, you're ready to move on: at this point you've equipped yourself with enough knowledge to use a real-world data API like Planet's API. From here, you can continue by following our API Quickstart guides to get up & running with the Planet API.


Rate this guide: