What is an API?

What is an API?
Published
August 12, 2021
Category

Developers

If you’ve read the Contentful docs, you’ll have seen that we provide a REST API and a GraphQL API to access and manage your content. But what is an API?

API stands for “Application Programming Interface,” which is a way to communicate between different software services. Different types of APIs are used in programming hardware and software, including operating system APIs, remote APIs and web APIs — like the APIs that Contentful provides. A web API is a set of tools that allow developers to send and receive instructions and data to and from web servers — usually in JSON format — to build applications. Read more about JSON on MDN.

APIs are everywhere

To look at how APIs work in ordinary life, let’s look at the APIs involved in posts. 

  • You read a post on the internet

  • When you land on the page, the web application contains instructions to request the data for the post via the API by a unique identifier — such as the URL slug of the post

  • If the data requested exists, it is sent back to the web page from the database via the API as JSON (such as the title, the published date, the article text and so on)

  • The data is then slotted into the appropriate HTML structure as programmed by the developer for you to read

This post will cover the fundamentals of what makes an API and how APIs communicate over the internet. But first, let’s take a look at the history of where it all began.

Where did it all start?

The concept of APIs has been around since the evolution of the first computers in 1940, when British computer scientists Marice Wilkes and David Wheeler worked on a software library for the Electronic Delay Storage Automatic Calculator (EDSAC). 

The EDSAC was programmed to accept a variety of instructions including add, subtract, print, load and store. This is similar to how modern web APIs interface with data, for example, “add blog post,” “delete blog post,” or “get blog post information.” The functionality of EDSAC was documented via a catalog of notes about its functionality and how to integrate it with other programs. This was the first example of the type of API documentation we know today!

What is a web API?

A web API is a set of tools that allow web developers to send and receive instructions and data over an internet connection to web servers. Many of the modern websites and web applications we use today are powered by APIs. Think Twitter, Instagram, Facebook and your favorite shopping websites.

In modern web applications, front-end code does not interact with a database directly. Instead, the data is sent and received via an API layer. APIs act as a middle layer, or contract, between backend logic and database operations and the front-end application that a user interacts with. 

An API layer:

  • ensures that the web page is allowed to make the request to send or receive data

  • confirms the request is in the correct format before sending it to the backend

  • returns the data in the expected format, along with some additional information

  • tells the web page if and why there is no data returned

What is an API diagram

So far, we’ve discussed how an API provides a middle layer to send data back and forth between backend databases and front-end applications. But what powers this data exchange? Let’s take a look at the foundation of data exchange on the web: HTTP.

A look at HTTP

HTTP — an acronym for HyperText Transfer Protocol — is a protocol that allows fetching resources, such as HTML documents and JSON data, over an internet connection. A protocol is defined as a system of rules that defines how data is exchanged within or between computers. HTTP defines a set of request methods that perform different actions when called. The most frequently used HTTP request methods are GET and POST.

As the verbs of the HTTP methods describe:

  • a GET request allows you to retrieve data via a URL

  • a POST request allows you to send additional information with a request via a URL to perform certain actions

Other HTTP methods that we won’t explore in this post include PUT, DELETE, HEAD, CONNECT, OPTIONS, TRACE and PATCH. To learn more about HTTP in depth, check out this article on MDN.

Before we get started with looking into GET and POST HTTP methods, let’s go over some HTTP terminology.

Sending information over HTTP

When you ask for data from an API, you make a request. When you receive data from an API, you receive a response.

Request and response body

In some HTTP methods, you will be required to send additional data inside a request body.

Successful HTTP responses will contain a response body that contains the data you requested via the API. 

HTTP headers

In addition to using different HTTP methods, you will often be required to send specific HTTP headers with a request and you may find specific HTTP headers accompanying a response. HTTP headers let the front end (client) and the backend (server) pass additional information with an HTTP request or response. An HTTP header is formatted as a key value pair separated by a colon:

"case-insensitive-header-name": "value as a string"

When making a request to the Contentful GraphQL API, you will be required to send an HTTP header with the request as follows:

authorization: "Bearer _your_contentful_access_token_value_"

This header ensures that the web page is authorized to make the request to receive data from the API and is detailed in the relevant documentation.

HTTP response status codes

Have you ever seen a web page that says “404, page not found? That code — 404 — is an HTTP response status code! In a browser, you’ll receive a 404 response status code if a URL is unrecognized by an application. From an API, you’ll receive a 404 response status code to indicate that the data you are requesting does not exist. You can find the HTTP response status codes returned to a browser in the browser network tab. 

404-not-found

HTTP response status codes are delivered with HTTP responses as a number. When requesting data from the Contentful GraphQL API using fetch in JavaScript, the HTTP status code is available as a status property on your response. 

The example code below requests the total number of blog posts available on my Next.js + Contentful starter blog. Notice the HTTP headers and request body sent with the request. When you run the code below, you’ll receive an HTTP 200 response, and 200 will be logged to the console. A 200 HTTP response code means the request was successful — and everything is “Ok!”

const data = await fetch(
  "https://graphql.contentful.com/content/v1/spaces/84zl5qdw0ore",
  {
    method: "POST",
    headers: {
      authorization: "Bearer _9I7fuuLbV9FUV1p596lpDGkfLs9icTP2DZA5KUbFjA",
      "content-type": "application/json",
    },
    body: '{"query":"{ blogPostCollection { total } }"}',
  },
).then((response) => {
  console.log(response.status); // 200
  return response.json();
});

There are five groups of HTTP response status codes that are categorized by the starting digit.

  1. Informational responses (100–199)

  2. Successful responses (200–299)

  3. Redirects (300–399)

  4. Client errors (400–499)

  5. Server errors (500–599)

Open the network tab in your browser and look for the 200 HTTP response status code for this web page. And if you’d like to explore a full list of HTTP response codes (including the silly response code 418 🙈), check out this article on MDN.

Now we’ve explored how you can send and receive with HTTP methods, let’s look at the two most common HTTP methods — GET and POST — in more detail.

HTTP GET

An HTTP GET request allows you to retrieve data via a URL. GET requests do not send a request body with the call to the API.

Here’s the Contentful Content Delivery API URL, which requests information about a single Contentful space. A Contentful space is like a bucket for your Contentful content, which has a name and unique ID. Notice the /spaces/ part of the URL, which defines that we’re asking for space information.

https://cdn.contentful.com/spaces/{space_id}?access_token={access_token}

The URL requires two pieces of data. The space_id, which is part of the URL, is the unique identifier of the space we’d like to get information about from the database. The access_token, which is a URL query parameter prefixed with ?, is an authentication token that tells the API that we’re allowed to make this request. This token will be verified by the backend when it receives the request. When you set up a Contentful space, you are instructed to generate an access token via the web app to communicate with the Contentful APIs. You may hear authentication tokens or similar credentials referred to as API Keys.

See the Contentful Delivery API at work by navigating to this URL in your browser: https://cdn.contentful.com/spaces/84zl5qdw0ore?access_token=_9I7fuuLbV9FUV1p596lpDGkfLs9icTP2DZA5KUbFjA

This particular URL requests information about the Contentful space that powers the Next.js starter blog using the appropriate space ID and access token. You should see the following data returned to your browser. The API has successfully returned the data you requested via the URL as JSON.

{
  "sys": {
    "type": "Space",
    "id": "84zl5qdw0ore"
  },
  "name": "[Live] nextjs-blog-starter",
  "locales": [
    {
      "code": "en-US",
      "default": true,
      "name": "English (United States)",
      "fallbackCode": null
    },
    {
      "code": "fr",
      "default": false,
      "name": "French",
      "fallbackCode": "en-US"
    }
  ]
}

Making an HTTP GET request using JavaScript

Here’s the same GET request above being made in JavaScript via fetch. GET is the default HTTP method in fetch, so it doesn’t need to be specified in the code.

const response = await fetch( "https://cdn.contentful.com/spaces/84zl5qdw0ore?access_token=_9I7fuuLbV9FUV1p596lpDGkfLs9icTP2DZA5KUbFjA",
).then((data) => data.json());

console.log(response);

Here’s the output in the browser console, which matches what we saw in the browser above.

Just as in the early example of the EDSAC, a good API has great documentation. API documentation describes the functionality of each API URL (or endpoint), how to send data in the correct format, and what data to expect from the API in return.

Here’s a screenshot from the Contentful Content Delivery API documentation, showing how to request information about a Contentful space.

Notice that the documentation specifies:

  • the parameters needed to perform a successful request 

  • the type of HTTP request (GET, POST, etc.)

  • the URL for the request

  • the expected response of a successful call 

The documentation also provides you with examples of how requests should be formatted in different programming languages and using different Contentful tools (such as SDKs and client libraries). Use the dropdown on this documentation page to see your options.

HTTP POST

POST requests require data to be sent via the request body rather than as URL parameters. For this reason, POST requests cannot be made using the address bar in a browser. This makes POST requests more secure than GET requests, and should always be used for API operations that deal with sensitive data, such as sending a login request. 

Making an HTTP POST request using JavaScript

Here’s an example of a POST request using fetch in JavaScript. This example posts a request to the Contentful GraphQL API, asking for the total number of blog posts in the Contentful space with space ID 84zl5qdw0ore. 

You may think it’s strange to request data by sending data — but GraphQL allows you to create, change and fetch data in a single HTTP call. That's why the POST method is the prefered way because you definitely don't want to update data with a GET request! This is also an example of sending extra HTTP headers with a request using JavaScript fetch (see authorization and content-type in the example below). 

const response = await fetch(
  `https://graphql.contentful.com/content/v1/spaces/84zl5qdw0ore`,
  {
    method: "POST",
    headers: {
      authorization: "Bearer _9I7fuuLbV9FUV1p596lpDGkfLs9icTP2DZA5KUbFjA",
      "content-type": "application/json",
    },
    body: '{"query":"{ blogPostCollection { total } }"}',
  },
).then((response) => response.json());

console.log(response);

If you’d like more information on how GraphQL works (it’s pretty cool!) — check out our GraphQL video course on our developer portal

That’s a wrap!

Now you know what an API is, how APIs work over HTTP and what you send and receive via GET and POST requests, have a go at putting your knowledge into practice by exploring the Contentful REST API and Contentful GraphQL API using your preferred programming language. 

If you’ve got any questions, come and join the Contentful Community Slack, where we’ll be happy to help you out. 

And finally, if you’ve built something with Contentful that you’re proud of, let us know on Twitter using the hashtag #BuiltWithContentful. Happy building!

About the author

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