API Keys Best Practices

-
5 min read

API Keys are one of the more popular ways to secure the access to a REST API. They are an easy method to grant and manage access to an API and track its usage. According to Blobr’s own API Portal report, 67% of the top 100 API companies use API Keys, while the other 33% prefer OAuth. However, API Keys require basic attention to avoid basic security threats. Here’s a checklist of the best practices to secure your API key.

URL Protocol

Never use HTTP. HTTPS is your friend.

How to use API keys?

Do not use API keys in URLs, they could be captured and exploited. HTTPS encrypts URLs but they may appear in clear at some point in the web server logs.

Don’t do:

https://api.company.com/path_to/api/verb?apikey=12345&field=value

The preferred option is to put them in the HTTPS header, or in the body for a POST.

Prefer this method:

from requests.auth import HTTPBasicAuth
import requests

auth = HTTPBasicAuth('apikey', "12345")
response = requests.get("https://api.company.com/path_to/api/verb,
					headers={'Accept': 'application/json'},
					auth=auth)

How to hide API keys?

In the example above, the API key is clearly displayed in the code, which is not a good practice.

The key should be retrieved from a database, a Secret Manager, or from your environment for instance.

from requests.auth import HTTPBasicAuth
import requests
import os

myapikey = os.environ.get("MY_API_KEY")
auth = HTTPBasicAuth('apikey', myapikey)
response = requests.get("https://api.company.com/path_to/api/verb,
					headers={'Accept': 'application/json'},
					auth=auth)

Implement Scopes

Avoid one-key-does-everything systems. If your API has only one security mechanism that allows full access to all the endpoints without restrictions, you’d better trust the people you are giving this sesame away.

Scopes should be used to limit the rights on objects or records that are manipulated and on operations allowed (read/write/update/delete).

The principle of Least Privilege (PoLP) should apply.

Rotate API keys

API keys shouldn’t last forever and your implementation should allow to regenerate them periodically.

When rotating a key, both the provider and consumers need to be updated simultaneously. If you first generate a new key on the API side, subsequent calls made by API consumers may end up with errors (unauthorized access) until the key is also updated on their side.

A good practice is to systematically create two keys for any API, a primary and a secondary.

On the consumer side, the caller may try first with the primary key and in case of error, fallback to the secondary one:

from requests.auth import HTTPBasicAuth
import requests
import os

myapikey = os.environ.get("MY_FIRST_API_KEY")
auth = HTTPBasicAuth('apikey', myapikey)
response = requests.get("https://api.company.com/path_to/api/verb,
headers={'Accept': 'application/json'},
auth=auth)
if response.status_code == 401:
    myapikey = os.environ.get("MY_SECOND_API_KEY")
		auth = HTTPBasicAuth('apikey', myapikey)
		response = requests.get("https://api.company.com/path_to/api/verb,
		headers={'Accept': 'application/json'},
		auth=auth)

By implementing this pattern, it is possible to rotate the two keys in two steps without getting any errors.

Begin by rotating the first key and update the database/secret/environment where the key is stored on the client side, then repeat the operation with the secondary key.

Final words

Those simple steps will greatly reduce the chance of security incidents, for both the provider and the consumer.

Stop wasting your Ad budget

Book your 30 minutes call to setup your goals and receive your first report.

Keep reading

September 14, 2021

Why APIs Are the Secret Ingredient for Success With IoT

How does IoT work? How come APIs are so important to the IoT sector?
February 9, 2023

Blobr raises €5 Million to help API providers understand how consumers convert and improve the developer experience

We just achieved ou Seed fundraising! Here's what it means for Blobr and for the users.
December 13, 2021

A step-by-step guide to creating your own API business

What are the steps to go through to create a cool & profitable API business on Blobr?