Card 03/ 12

ConceptDifficulty: Beginner1 min

API Keys: A Shared Secret That Names a Project

An API key says which project is calling, not which person, and anyone who copies it becomes that project.

An API key is a long random secret the API issues to a project or account, which the caller sends with every request to say which project is calling. It proves possession of the secret and nothing else: it does not name a person, and anyone who copies it can call as that project. Keys suit server-to-server calls and usage metering, they travel in a request header, and access is cut off by revoking the key.

text
GET /v1/forecasts?city=Lisbon HTTP/1.1
X-Api-Key: sk_live_4f8a2c9e71b3d05a6e
Host: api.example.com

GET /v1/forecasts?city=Lisbon&api_key=sk_live_4f8a2c9e71b3d05a6e HTTP/1.1
Host: api.example.com
An illustrative request with the key in a header, and the same key in a query string, which leaks

What proves the caller. A value with enough randomness that it cannot be guessed, often prefixed to show what it is, such as sk_live_ for a secret production key. The server stores only a hash of it, like a password, so a database leak does not leak the keys.

Where it travels. In a header, either a custom one such as X-Api-Key or Authorization. Never in the URL: query strings are written to server logs, proxy logs and browser history, and are passed on in the Referer header, so a key there is shared with everyone who reads those.

Which client it suits. A partner's back end or a script, where the secret lives on a server. It does not suit browser code or a mobile app, because anything shipped to a device can be extracted, and then every copy of the app shares one stolen identity.

How access is cut off. Revoke the key, and it stops working at once. Issue several keys per project, with names, so one can be rotated or revoked without stopping everything.

So use API keys to identify projects calling from servers, keep them in headers, and plan for revoking one.