API Keys: API Authentication Methods & Examples

Danielle Gaither
by Danielle Gaither on December 21, 2022 8 min read

“How am I going to keep this secure?” is a crucial question when building any piece of software. This question is especially critical for APIs, which provide programmatic access to important systems. After all, authentication shouldn’t be an afterthought but instead built into the very fabric of your API.

Simply put, authentication is the act of verifying that you are who you claim to be. Think of it as needing a key to open a locked house. The lock only accepts the right key and the key grants you access to what’s inside. (For a more extensive primer on authentication and authorization, see this guide.)

There are many methods of API authentication, such as Basic Auth (username and password) and OAuth (a standard for accessing user permissions without a password). In this post, we’ll cover an old favorite, the API key, and discuss how to authenticate APIs.

Many early APIs used API keys. While they might not be the latest standard in security now, they were often an improvement over passing other credentials in API code. There are drawbacks to API keys, but they’re also a simple way to secure access. Of course, not everyone agrees on how to pass keys to an API or how API authentication and keys work. We’ll cover that, as well as some examples, in this post.

But first, why would you want—or not want—to choose API key authentication? Let’s look at some authentication methods and API authentication best practices.

Pros and Cons of API Key Authentication

You’ll find varying opinions about choosing API key authentication over other authentication methods. It remains a popular method, but developers should be aware of its tradeoffs. Let’s look deeper.

One of the clear advantages of API key authentication is its inherent simplicity, an authentication best practice. The method uses a single authentication key that allows you to authenticate just by including the key. This simplicity also allows a user to make calls easily, with cURL, with interactive docs, or even in their browser.

Another advantage is API key authentication’s popularity. Developers are familiar with API keys, which means they don’t have to spend extra time understanding how they work. The easier and quicker it is to authenticate to your API, the more likely the developer will find success. Whether that developer is within your own company or an external partner, you want your API to be easy to use.

On the other hand, simplicity may raise security concerns. What happens if someone comes upon an API key that is not their own? In most cases, they can use the API key with all the privileges of the rightful owner. Depending on the API, they may be able to retrieve all its data, add incorrect content, or even delete everything.

One precaution that some API designers take is to use API keys only for read-only data. For APIs that don’t need write permissions, this is an easy way to handle authentication while limiting risk. However, this approach limits APIs that may require more granular permissions.

How to Pass API Keys in Headers

If you determine that the simplicity of API keys makes sense for your use case, there are several places where API keys can be passed in your API design.

The most popular API key location for modern APIs is in headers. However, that’s not enough information: where in the headers should you include the API key? There are several methods that we’ll cover next.

Before that, an important note: as with all API requests, use HTTPS (TLS, the successor to SSL) to ensure that data is encrypted in transit.

x-api-key

The most popular choice for including API keys in headers, perhaps due to its usage by AWS API Gateway, `x-api-key` is a custom header convention for passing your API key. For more on API gateway authentication, see this post about API gateways.

GET / HTTP/1.1
Host: example.com
X-API-KEY:  abcdef12345

Basic Authentication

How long should an API key be? It depends. Earlier, we suggested Basic Auth as an alternative to API keys. Basic Auth and API keys can also be used together. You can pass the API key via Basic Auth as either the username or password. Most implementations pair the API key with a blank value for the unused field (username or password).

GET / HTTP/1.1
Host: example.com
Authorization: Basic bWFnZ2llOnN1bW1lcnM=

You will need to base64-encode the `username:password` content, but most request libraries do this for you.

Bearer Authentication

Some APIs use the `Authorization` header to handle the API key, usually with the Bearer keyword. This method is also used for other tokens, such as those generated by OAuth.

The client must send this token in the `Authorization` header when making requests to protected resources:

Authorization: Bearer abcdef12345

What about non-header locations for API keys? You can find them in query strings or even the data body.

Other API Key Locations

Though the header has become the preferred location for API keys, there are non-header methods still used by many APIs. As a developer using APIs, you may spot these methods in the wild. As an API designer, you’ll probably want to stick to the headers, as we’ll explain.

Query String

A popular method for early APIs, passing an API key through a query string in a URL is certainly easy. However, this method can risk API key exposure since, despite encryption, the parameters can be stored in web server logs.

curl -X GET "https://example.com/endpoint/?api_key=abcdef12345"

If you use the query string method, you’ll want to make sure that there’s a low risk of the API key being shared.

Request Body Parameter

Another method we’ve seen, especially in older APIs, is to pass an API key in the POST body as JSON:

curl -X POST
	`https://example.com/endpoint/’ 
	-H ‘content-type: application/json’ 
	-d ‘ {
		“api_key”: abcdef12345”
	}’

The most significant drawback to this method is that authentication is mixed in with other data. It also encourages poor REST practices, as simple reads from the API would need to be sent a POST request instead of GET.

JavaScript API

Finally, you may see API keys used with front-end JavaScript APIs, which provide in-browser access to API functionality. In these cases, the API key is passed one of two ways. Either the key is passed with the call to the script or in the JavaScript itself.

For example, Google Maps passes the key in the query string to the JavaScript:

 <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" type="text/javascript"></script> 

Keen Dataviz, on the other hand, passes the API in a constructor:

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY'
});

In both cases, the companies take additional steps to secure the API calls. This is important because the API keys are essentially public, as they are easily discoverable if you view the source. Google Maps allows developers to restrict its usage on certain websites. Keen has separate read and write API keys.

API Key Authentication using OpenAPI

In addition to human-readable API documentation, an OpenAPI definition is a must when designing APIs. You can describe your entire API in a machine-readable file (YAML or JSON). The format is meant to cover the many ways developers create RESTful APIs and support security schemes, including API keys, so it is flexible enough for any of the methods we’ve discussed.

For example, here is the security section of Stripe’s OpenAPI document, showing the two header approaches supported for its API keys:

  securitySchemes:
    basicAuth:
      description: 'Basic HTTP authentication. Allowed headers-- Authorization: Basic
        <api_key> | Authorization: Basic <base64 hash of `api_key:`>' scheme: basic type: http bearerAuth: bearerFormat: auth-scheme description: 'Bearer HTTP authentication. Allowed headers-- Authorization: Bearer <api_key>' scheme: bearer type: http 

A machine-readable API specification allows you to test the implementation against the specification throughout your API development lifecycle without extensive effort.

This quick tour should be just enough to get you started with API key authentication but see our longer series on planning and designing your API authentication strategy for a more comprehensive view.

Stoplight Platform makes it easy to design your API visually—including security definitions around any authentication—with OpenAPI. We hope you enjoyed these API authentication and authorization tips!

Share this post

Stoplight to Join SmartBear!

As a part of SmartBear, we are excited to offer a world-class API solution for all developers' needs.

Learn More
The blog CTA goes here! If you don't need a CTA, make sure you turn the "Show CTA Module" option off.

Take a listen to The API Intersection.

Hear from industry experts about how to use APIs and save time, save money, and grow your business.

Listen Now