Find a course

Module 4: Using Real APIsLesson 9 of 1214 min

Authentication, API Keys and Rate Limits

Understand how APIs identify callers with API keys, bearer tokens and OAuth, keep secrets out of client code, and respect the rate limits servers enforce.

Step 1 of 13Learn

Who is calling?

Most APIs need to know who's making each request: to bill usage, to apply limits, and above all to decide what that caller may see. Two separate questions are involved:

  • Authentication: who are you? Proving identity, with a key, a token or a password.
  • Authorization: what are you allowed to do? Checking permissions once identity is known.

That's exactly the 401 vs. 403 split from earlier: 401 means authentication failed; 403 means authentication worked but authorization said no.

The simplest scheme is an API key: a long random string the provider gives you, sent with every request, usually in a header:

GET /v1/forecast?lat=48.85&lon=2.35 HTTP/1.1
Host: api.weather.example
X-API-Key: 9f8c2e71b4d04a6e8f1a2b3c4d5e6f70

Some APIs accept the key as a query parameter (?api_key=...), but headers are better: URLs end up in server logs, browser history and analytics tools, which leaks the key.

API keys identify an application or account, not an individual user. They're ideal for server-to-server calls, such as your back end calling a weather or email service. They're a poor fit when your app acts on behalf of many different users, each with their own data; that's where tokens and OAuth come in.

Step 2 of 13Practice · Match the pairs

Match each question to the concept it belongs to.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. "Is this token valid, and whose is it?"
  2. "May this user delete invoices?"
  3. The response when no valid credentials are sent
  4. The response when valid credentials lack permission

Step 3 of 13Learn

Bearer tokens and OAuth

Modern APIs commonly use bearer tokens, sent in the standard Authorization header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

"Bearer" means whoever holds (bears) the token can use it, like a ticket. Tokens are usually short-lived, often valid for minutes to an hour, so a stolen token stops working soon. A longer-lived refresh token can be exchanged for a new access token without asking the user to sign in again.

Many tokens are JWTs (JSON Web Tokens): three base64url-encoded parts separated by dots, containing JSON claims such as the user ID and expiry time, plus a signature that lets the server detect tampering. A JWT is signed, not encrypted by default: anyone holding it can decode and read its contents, so never put secrets inside one.

OAuth 2.0 is the standard way to let an app act on a user's behalf without ever seeing the user's password. When you click "Connect your calendar" in a scheduling app:

  1. The app redirects you to the calendar provider's sign-in page.
  2. You sign in there and approve specific permissions, called scopes, such as "read events".
  3. The provider redirects back to the app with a short-lived code.
  4. The app's server exchanges that code for an access token.
  5. The app calls the calendar API with Authorization: Bearer <token>, limited to the approved scopes.

You can revoke the app's access at any time without changing your password.

Step 4 of 13Practice · Put in order

Put the steps of a typical OAuth 2.0 "Connect your account" flow in order.

Drag the items, or use the arrow buttons, to put them in order.

  1. The user signs in at the provider and approves the requested scopes
  2. The app redirects the user to the provider's sign-in page
  3. The app calls the API with the token in the Authorization header
  4. The app's server exchanges the code for an access token
  5. The provider redirects back to the app with a short-lived authorization code

Step 5 of 13Diagram

OAuth 2.0 "Connect your account", step by step

OAuth 2.0 "Connect your account", step by stepProcess diagram: App sends you to provider → You sign in and approve → Provider returns a code → App swaps code for tokens → App calls the API.App sends you toproviderYou sign in andapproveProvider returns acodeApp swaps code fortokensApp calls the API

Tap a shape with to see more.

App sends you to provider

With its client ID and the scopes it wants.

You sign in and approve

Your password goes only to the provider, never to the app.

Provider returns a code

Short-lived and single-use, sent back via the redirect URL.

App swaps code for tokens

Server to server, using the app's client secret.

App calls the API

Authorization: Bearer <access token>, limited to the approved scopes.

Step 6 of 13Learn

Keeping secrets secret

API keys and tokens are passwords for machines. Leaked keys are one of the most common causes of security incidents and surprise bills, because automated bots scan public code repositories for keys within minutes of a push.

Rules worth following:

  • Never put secret keys in front-end code. Anything shipped to a browser or a mobile app can be extracted by users. If a browser app needs a secret-key API, call your own back end, which adds the key and forwards the request.
  • Don't commit keys to version control. Keep them in environment variables or a secrets manager, and list files like .env in .gitignore.
  • Use the narrowest permissions. Many providers let you create keys restricted to certain endpoints, read-only access or specific domains.
  • Rotate keys regularly and immediately after any suspected leak. Deleting a leaked key from the latest commit isn't enough; it's still in the history and possibly already copied.
  • Always use HTTPS, so credentials can't be read in transit.

Some providers issue publishable keys designed to be public, such as a payments provider's key for a checkout form, alongside secret keys that must stay on the server. Read the docs to know which kind you have.

Step 7 of 13Practice · What would you do?

What would you do?

A student builds a weather website in plain HTML and JavaScript. To call a paid weather API, they put the secret API key directly in script.js. What's the main risk, and the right fix?

Step 8 of 13Practice · Diagram

Keep the secret key on a server you control

Where should the secret API key live?

Tap the shape that answers the question, then press Check.

Keep the secret key on a server you controlProcess diagram: Browser page → Your backend → Weather API → Data back to the page.BrowserpageYour backendWeather APIData back tothe page
Browser page

Calls your endpoint, such as /api/weather?city=Oslo. No key here.

Your backend

Reads the key from an environment variable and adds it to the request.

Weather API

Sees a valid key; replies to your backend.

Data back to the page

Your backend can also cache results and limit abuse.

Step 9 of 13Learn

Rate limits

APIs limit how many requests each client may make in a time window, such as 100 requests per minute or 10,000 per day. Rate limits protect the service from overload and abuse, and keep one heavy user from slowing everyone else down.

When you exceed the limit, the server returns 429 Too Many Requests, often with headers telling you how to behave:

HTTP/1.1 429 Too Many Requests
Retry-After: 20
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1767225600

Retry-After says how many seconds to wait. The X-RateLimit-* headers (names vary by provider; a standard RateLimit header is being developed) report your limit, how many requests remain and when the window resets.

Being a good API citizen:

  • Read the headers and slow down before you hit zero, not after.
  • Cache responses that don't change often instead of re-requesting them.
  • Batch work: one request for 100 items beats 100 requests for one item each, if the API supports it.
  • Spread out scheduled jobs rather than firing everything at midnight.

A little arithmetic helps plan bulk jobs. With 5,000 records and a limit of 60 requests per minute, one request per record takes at least 5,000 ÷ 60 ≈ 84 minutes.

Step 10 of 13Try the calculator

Rate limit planner

Estimate how long a bulk job takes when every item needs requests and the API caps your rate.

Total requests
5,000
Minimum time (minutes)
83.3
Minimum time (hours)
1.39

Step 11 of 13Practice · Work it out

A script must update 3,000 products. Each update needs 2 requests (read, then write), and the API allows 120 requests per minute. What is the minimum time, in minutes, the job can take without hitting the limit?

Step 12 of 13Practice · Chart

A script ramps up against a 120-per-minute limit

In which minute does the script start receiving 429 Too Many Requests?

Tap the point that answers the question, then press Check.

A script ramps up against a 120-per-minute limitLine chart with 6 categories: Min 1: Requests sent 60, Limit 120; Min 2: Requests sent 90, Limit 120; Min 3: Requests sent 115, Limit 120; Min 4: Requests sent 140, Limit 120; Min 5: Requests sent 120, Limit 120; Min 6: Requests sent 118, Limit 120.050100150Requests per minuteMin 1Min 2Min 3Min 4Min 5Min 6
Illustrative example.
A script ramps up against a 120-per-minute limit
ItemRequests sentLimit
Min 160120
Min 290120
Min 3115120
Min 4140120
Min 5120120
Min 6118120

Step 13 of 13Practice · True or false

A JWT access token is encrypted, so it is safe to store a user's password or other secrets inside it.