正在加载,请稍候…

How to Debug API Requests: A Practical Guide for Developers

Walk through a systematic approach to debugging failed API calls — from reading HTTP status codes and parsing URLs to inspecting headers and decoding JWT tokens.

APIs Fail in Predictable Ways

When an API call fails, most developers immediately open the network tab or start adding console.log statements. That works, but there is a faster mental model: every API failure falls into one of five categories, and the HTTP status code tells you which one. Once you know the category, the fix is usually obvious.

Step 1: Read the Status Code

The status code is the single most important diagnostic signal. Never skip it.

4xx — You sent something wrong

Code Meaning Most Common Cause
400 Bad Request Malformed JSON, wrong field type, missing required field
401 Unauthorized Missing or expired token, wrong auth scheme
403 Forbidden Valid token but insufficient permissions
404 Not Found Wrong URL path, resource does not exist, wrong ID
405 Method Not Allowed POST where GET is expected, or vice versa
409 Conflict Duplicate record, stale update, race condition
413 Payload Too Large File too big, body exceeds server limit
422 Unprocessable Entity Valid JSON structure but invalid field values
429 Too Many Requests Rate limited — back off and retry

5xx — The server broke

Code Meaning Action
500 Internal Server Error Bug on their side; check their status page
502 Bad Gateway Server down or restarting
503 Service Unavailable Overload or maintenance
504 Gateway Timeout Server too slow; retry with backoff

A 5xx is almost never your fault. Check the service status page before debugging your own code.

Step 2: Inspect the URL

More API bugs trace back to malformed URLs than developers expect. Check these systematically:

Protocol — http vs https. Many APIs refuse plain HTTP connections or silently redirect them.

Host — A single typo connects you to the wrong server or nowhere at all.

Path — Watch for a missing leading slash, a doubled slash, or the wrong version prefix (v1 vs v2).

Query parameters — Values must be URL-encoded. A space must become %20; an ampersand in a value must become %26. Always use encodeURIComponent() in JavaScript when building URLs dynamically.

// Wrong — breaks if name contains &, =, or spaces
const url = `https://api.example.com/search?name=${name}`;

// Correct
const url = `https://api.example.com/search?name=${encodeURIComponent(name)}`;

Step 3: Check Authentication

The difference between 401 and 403 is important:

  • 401 — The server does not know who you are. Credentials are missing, expired, or malformed.
  • 403 — The server knows who you are but will not permit the action. This is a permissions issue.

For JWT Bearer tokens, decode the token and check the exp claim (expiry as a Unix timestamp), the aud claim (intended audience), and any scope or permissions claims. You do not need the signing secret to read the claims — only to verify the signature.

For API keys, verify the key is in the correct header and confirm you are using the key for the right environment. Production keys typically do not work on staging endpoints.

For Basic Auth, the header value is base64(username:password). Decode it to confirm the credentials are correct.

Step 4: Validate the Request Body

400 and 422 errors usually mean something is wrong with the request body. Read the error response carefully — it typically identifies the specific field that failed.

Common body problems:

Wrong Content-Type — Sending JSON without the Content-Type: application/json header causes some servers to ignore the body entirely.

Trailing commas — Valid in JavaScript but invalid in JSON. The value {"key": "value",} will fail JSON parsing on most servers.

Wrong types — Sending the string "123" where an integer 123 is required, or "true" where a boolean true is expected.

Null versus missing — Some APIs treat an explicit null differently from an omitted field.

Step 5: Diagnose CORS Errors

CORS errors occur only in browsers. The same request may succeed from curl or Postman but fail in your web app, because browsers enforce same-origin policy and require servers to explicitly permit cross-origin requests.

Signs of a CORS problem: the browser console shows "Access to fetch has been blocked by CORS policy," the network tab shows a status of 0, and the request works fine from Postman.

The fix must happen on the server. CORS cannot be disabled from the browser. Check whether the server responds with Access-Control-Allow-Origin set to your origin or *, and whether it handles the preflight OPTIONS request for routes that require an Authorization header.

Step 6: Isolate with curl

Use curl to remove all client-side variables. If a request works in curl but not in your code, the bug is in your code. If it works in curl but not in the browser, it is CORS.

# GET with auth header
curl -v -H "Authorization: Bearer your_token" https://api.example.com/users

# POST with JSON body
curl -v -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your_token" \
  -d '{"name":"test","email":"test@example.com"}' \
  https://api.example.com/users

The -v flag shows full request and response headers. Always include it when debugging — most bugs hide in the headers.

Debugging Toolkit

Problem Tool
Parse and break down a URL URL Parser
Decode and inspect a JWT JWT Parser
Decode a Base64 auth header Base64 Decoder
Look up an HTTP status code HTTP Status Codes
Test regex against response data Regex Tester

→ Start with the URL Parser to break down any endpoint URL and catch encoding or path mistakes immediately.