This guide covers what you need to call a third-party HTTP API from your own code and keep the integration working when things go wrong: how a request is put together, how the two common authentication schemes work, which errors to retry, and how to test the result. It is written for developers making their first integrations. The examples are JavaScript and run on Node.js 18 or later.
What an API call consists of
An HTTP API exposes operations at URLs, called endpoints. A request to an endpoint has four parts: a method, a URL, headers, and sometimes a body.
The method states the intent. GET reads, POST creates or runs an operation, PUT and PATCH update, and DELETE removes. The headers carry metadata, most importantly the credentials and the Content-Type of the body. The body, where there is one, is usually JSON.
The response comes back with a status code, headers and a body. The status code is the first thing to check. Codes in the 200s mean success, the 400s mean the request was wrong in some way and will fail again if sent unchanged, and the 500s mean the server failed. The response headers often tell you how much of your rate limit is left.
Every provider documents its endpoints, parameters, limits and error format. Read that reference before writing code, because the details that matter (which header carries the key, what a validation error looks like, what the rate limit is) differ from one API to the next.
Authenticate with an API key
An API key is a secret string that identifies your account. You send it with every request, usually in a header. The header name varies by provider: some use Authorization: Bearer <key>, others a custom header. APIStack uses x-api-key, as described in the authentication docs.
This request Base64-encodes a string with an APIStack API. The key is read from an environment variable, not written into the source file:
const response = await fetch('https://apistack.online/api/utilities/base64/v1', {
method: 'POST',
headers: {
'x-api-key': process.env.APISTACK_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({ operation: 'encode', text: 'Hello, world' })
})
const result = await response.json()
console.log(response.status, result)API keys are simple and suit server-to-server calls. Their weakness is that a key is a long-lived password: anyone who has it can use your quota until you revoke it.
Authenticate with OAuth 2.0
An API key acts as your application. OAuth 2.0 is for the other case, where your application acts on behalf of a user, such as reading their calendar or posting to their account, without ever seeing their password. The user approves the access on the provider's site, and your application receives a token limited to the scopes they approved.
For applications with users, the standard flow is the authorization code grant, defined in RFC 6749, with the PKCE extension from RFC 7636. It has three steps:
- Your application redirects the user to the provider's authorization URL, with your client ID, the requested scopes, a redirect URI and a PKCE code challenge.
- The user signs in and approves. The provider redirects back to your redirect URI with a short-lived authorization code.
- Your server exchanges the code for an access token at the provider's token endpoint.
The exchange in step 3 is a form-encoded POST, not JSON. The redirect_uri must match the one used in step 1, and code_verifier is the secret your application generated before computing the code challenge:
const tokenResponse = await fetch('https://auth.example.com/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code: authorizationCode,
redirect_uri: 'https://yourapp.example/callback',
client_id: process.env.OAUTH_CLIENT_ID,
client_secret: process.env.OAUTH_CLIENT_SECRET,
code_verifier: codeVerifier
})
})
if (!tokenResponse.ok) throw new Error(`Token exchange failed: ${tokenResponse.status}`)
const { access_token, refresh_token, expires_in } = await tokenResponse.json()The access token then goes in the Authorization header of each API call:
const profile = await fetch('https://api.example.com/user', {
headers: { Authorization: `Bearer ${access_token}` }
})Access tokens expire, typically within minutes or hours. When one does, the API answers 401 and your server uses the refresh token to get a new one without involving the user again. In practice, use the provider's SDK or a maintained OAuth library for this flow. The details that are easy to get wrong, such as state checking and token storage, are covered in the IETF's security guidance, RFC 9700.
Handle errors
fetch only rejects when the request could not be completed at all, for example on a DNS failure or a timeout. A 404 or a 500 is a normal resolved response, so the code has to check response.ok or response.status itself. Skipping that check is the most common bug in a first integration: the code parses an error body as if it were data.
Errors fall into two groups, and they need different handling.
Errors that will not fix themselves should be reported, not retried. A 400 or 422 means the request is invalid, 401 means the credentials are missing or wrong, 403 means the credentials are valid but not allowed to do this, and 404 means the resource does not exist. Log the response body, because a well-designed API says what was wrong.
Errors that may pass are worth retrying: network failures, timeouts, 429 (rate limited) and the 500, 502, 503 and 504 family. Retry with exponential backoff, which means waiting longer after each failure, and add a random component so that many clients do not retry at the same instant. If the response has a Retry-After header, wait at least that long.
The function below does this. It sets a ten-second timeout, retries only the transient failures, honours Retry-After, and gives up after four attempts:
const RETRYABLE = new Set([408, 429, 500, 502, 503, 504])
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))
async function callApi(url, options = {}, maxAttempts = 4) {
for (let attempt = 1; ; attempt++) {
let response
try {
response = await fetch(url, { ...options, signal: AbortSignal.timeout(10_000) })
} catch (error) {
if (attempt === maxAttempts) throw error
}
if (response) {
if (response.ok) return response.json()
if (!RETRYABLE.has(response.status) || attempt === maxAttempts) {
const body = await response.json().catch(() => ({}))
throw new Error(`${response.status}: ${body.error || response.statusText}`)
}
}
const retryAfter = Number(response?.headers.get('Retry-After'))
const delay = retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 250 + Math.random() * 250
await sleep(delay)
}
}Respect rate limits
Almost every API limits how often you can call it, per minute, per month or both. Find the limits in the documentation before you design the integration, because they decide whether you can call the API on every user action or need to batch and cache.
On APIStack, for example, the free plan allows 1,000 calls a month at up to 10 calls a minute. A call over a limit returns 429 with a Retry-After header. The limits section of the docs lists the figures for each plan.
Two habits keep you inside any limit. Cache responses that do not change between calls, such as reference data or the result of validating the same input twice, so repeated lookups cost nothing. And when you process many items, run them through a queue with a fixed concurrency instead of firing all the requests at once.
Test the integration
Start outside your code. Make the request with curl or an API client until you get the response you expect. That separates problems with the request from problems with your program.
In automated tests, do not call the real API. Tests that depend on a network service are slow, fail for unrelated reasons, and use up your quota. Put the API calls behind one module in your code and replace that module, or the HTTP layer under it, with canned responses. Include the failure cases: a 429, a 500, a timeout, and a response missing a field you rely on. Those paths are the ones that rarely run in development and matter most in production.
Keep a small number of tests that do call the real service, run on a schedule and not on every commit, to catch the provider changing its behaviour.
Finally, log every outgoing call with its endpoint, status code and duration, and never the key or token. When an integration misbehaves, that log is how you find out whether the fault is on your side or the provider's.
Summary
- Check the status code of every response;
fetchdoes not throw on4xxor5xx. - Keep API keys and client secrets on the server, in environment variables or a secret manager.
- Use API keys when your application acts as itself, and OAuth 2.0 with PKCE when it acts for a user.
- Retry only transient failures, with exponential backoff and jitter, and honour
Retry-After. - Test against canned responses, including the error cases, and log every outgoing call.