Back to Explore
GuideVibeFix editorialUpdated Nov 24, 2026

Debugging JSON APIs in Practice: curl Requests, jq Field Extraction, and Status-Code Triage

When an API call fails, take it out of the code and talk to it directly: curl sends one request, jq pulls the JSON apart, and the status code tells you whose problem it is. This guide works a 4-book mock API end to end: 4 books, stock 40, total value 1671, a 404 with 'book not found', a 201 order totalling 174, and a broken JSON that makes jq exit 5. curl 8.5.0, jq 1.7.

Real photo: a person pointing at code on a laptop screen, with two monitors behind also showing code

AI wrote you a snippet that calls an API, you run it full of hope, and instead of the data you wanted you get an error you cannot read, or nothing at all. The least useful thing to do then is to stare at the code, or to ask the AI to generate it again with a different phrasing. What actually works is to take the API call out of the code and talk to the API on its own: send one request with curl, see exactly what the server sends back, and pull the JSON apart with jq. This guide covers that craft: get the raw JSON first, extract fields with jq, read the status code before the body, send a POST, recognise broken JSON, and finish with a debugging checklist. Everything runs against a local mock API, a fictional "Morning Light Bookstore" books API. The demo script is demo245_zh.py in the draft folder, the English rerun is rerun_en_demo245_g1.py, and the numbers are identical in both runs. The mock returns Chinese book titles; this English text translates them, and every number quoted here matches the transcripts. Local tool versions are curl 8.5.0 and jq 1.7, and every option used here exists in newer versions too.

First, the framing. Debugging an API is not "fixing the server", it is "asking the question clearly". Most API problems are one of four things: the URL is wrong, the parameters are wrong, something failed on the server side, or the response is not in the format you assumed. curl and jq split the job exactly along those lines: curl sends the request and brings back the raw response, jq takes the JSON response apart so you can see every field. You do not need all of jq's syntax or all of curl's hundreds of options first; the dozen or so usages below handle most everyday API problems.

Get the raw JSON first: do not pipe blindly

Section 1 of the demo script fetches the book list with curl, saves it to a file, and only then looks at it:

curl -s http://127.0.0.1:18765/api/books > books.json
jq . books.json

What it does: -s is silent mode, no progress meter, only the response body; > books.json saves the body to a file; jq . pretty-prints the JSON in the file, where . means "output as-is". In the measured run the curl exit code was 0, and the first line of the raw JSON was [{"id": 1, "title": "Python Basics", "price": 36, "stock": 12}, ... (titles translated here), an array of 4 books. Why save to a file first: debugging is ruined by "I glanced at it and it scrolled past". You only get one chance to see the raw response, and once it is saved you can try different jq expressions against it again and again without re-sending the request. Another reason is that terminal output scrolls away, while a file lets you compare line by line. One detail: always add -s. Without it curl prints a progress meter that mixes into the JSON, and anything you copy-paste carries garbage with it. Once you trust the API, piping directly with curl -s URL | jq . is fine.

Once you have the raw JSON, ask three questions before extracting any field. First, is this response JSON at all? If it starts with <!DOCTYPE html>, it is not API data at all but an error page: the URL is probably wrong, or the API wants you to log in and redirected you to a login page. Second, is it an array or an object? Arrays are wrapped in square brackets, objects in curly braces, and the jq syntax for each is completely different, so read the shape before writing the filter. Third, are the fields you assume really there? You might assume every book has a stock field, but if one does not, the code that reads it breaks. The 4 books in the demo are neatly structured, each with an id, a title, a price and a stock count, which is exactly the "look first, then act" habit this guide is teaching.

Extract fields with jq: dots, brackets and pipes

Section 2 of the demo script is the jq basics, all run against the books.json saved above:

jq length books.json
jq -r '.[1].title' books.json
jq '.[1].price' books.json
jq '[.[].stock] | add' books.json
jq '[.[] | .price * .stock] | add' books.json
jq -r '.[] | select(.price > 40) | .title' books.json

What it does: jq length counts 4 books; .[1].title takes the title of the second book, "Bash Handbook" — arrays count from 0, so .[1] is the second item; .[1].price takes its price, 58; [.[].stock] | add adds the four stock counts 12, 8, 15 and 5, for a total of 40; [.[] | .price * .stock] | add computes each book's stock value first and then sums them, giving 1671; the last line filters for books priced over 40, which are "Bash Handbook" and "Regex Cheat Sheet". Why it is written this way: jq thinks in "filters joined to filters". . is the whole input, .title reads one field of an object, .[1] takes one element of an array, and the pipe | hands the previous step's output to the next, just like a shell pipe. -r is short for raw output: strings come out without quotes. Without -r a title prints as "Bash Handbook" with quotes; with it you get a clean Bash Handbook that will not carry an extra pair of quotes into the next request.

The chart below is the answer to that arithmetic problem: the stock value of each of the four books, 36x12 is 432, 58x8 is 464, 42x15 is 630, 29x5 is 145, and the four add up to 1671 yuan.

Bar chart of the four demo books' total stock value: Python Basics 432 yuan, Bash Handbook 464 yuan, Regex Cheat Sheet 630 yuan, Git in Practice 145 yuan, total 1671 yuan

select deserves a few more words. It is the most practical filter in jq: .[] | select(.price > 40) means "split the array into one book at a time and keep only the ones priced over 40". Debugging is full of exactly this: from dozens of records, find the ones with an unusual price, the ones whose status is not 200, the ones with an empty field. Learn select first, then | add, length and sort_by, and you can do simple statistics on API data right in the terminal instead of writing a Python script just to look at a number. One more defensive idiom: if a field might be missing, write .stock // 0, meaning "use it if it exists, otherwise treat it as 0", so jq does not stop and null does not silently poison the calculation that follows.

Status code first, body second: a 404 is not curl's fault

Section 3 of the demo script is the most important section in this guide, because it corrects the most common misunderstanding:

curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:18765/api/books/99
curl -s http://127.0.0.1:18765/api/books/99 | jq -r .error
curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:18765/api/books/2
curl -s -o /dev/null -w "%{content_type}" http://127.0.0.1:18765/api/books

What it does: book 99 does not exist, the status code is 404 and the error message is book not found; book 2 exists, the status code is 200; the book list's response Content-Type is application/json. Why it is written this way: -o /dev/null throws the body away and -w "%{http_code}" prints only the status code, so you see the number at a glance. The status code is the server's first sentence to you, and it matters more than the body: 2xx means success, 3xx means redirect, 4xx means the problem is on your side, 5xx means the problem is on the server's side. A 404 means "what you asked for does not exist", and only then is it worth reading the error message in the body; a 500 means "the server itself failed", and changing your request parameters will not help — you need the server logs. The demo's 404 comes with book not found, so you can tell at a glance that the id was wrong, not that the network was down.

One trap here needs its own paragraph: curl's exit code is not the HTTP status code. In the command above that asked for book 99, the server clearly answered 404, and curl still exited with 0 — because for curl, "successfully receiving a response" counts as success, even if that response is a 404. Many beginners write curl URL && echo success to check whether an API is up, and a 404 prints "success" for exactly this reason. The correct approach is the demo's: take the status code out separately with -w "%{http_code}" and judge it yourself, or add --fail so curl returns a non-zero exit code on 4xx and 5xx. And a word about Content-Type: it tells you what format the body is in. Only application/json is safe to hand to jq; if it is text/html, you are almost certainly looking at an error page, jq will fail, and there is no point wrestling with jq — go back and check the URL and the login state.

POST an order: decide the format before you send data

Section 4 of the demo script places an order with POST:

curl -s -X POST -H "Content-Type: application/json" \
  -d '{"book_id": 2, "qty": 3}' \
  -w "\nHTTP:%{http_code}" http://127.0.0.1:18765/api/orders

What it does: it orders 3 copies of book 2, the server answers 201, the order id is 101, the unit price is 58 and the total is 174. Why it is written this way: -X POST sets the request method; -H "Content-Type: application/json" tells the server "what I am sending is JSON"; -d carries the data itself; -w "\nHTTP:%{http_code}" prints the status code on its own line after the body. A 201 means "created" and is the most common status code after a successful POST — seeing 201 after a POST means the thing was really created; a 200 can also mean success, but 201 is the surer sign. The total of 174 is computed by the server, 58 times 3 is 174, matching your own calculation, and that cross-check matters: if you calculated 174 and the server answered 0 or 58, your understanding of the API and the server's implementation disagree, and you should stop and compare field names and units.

The three most common POST mistakes all sit in -d and -H. First, forgetting -H "Content-Type: application/json": the server receives JSON but does not know it is JSON, tries to parse it as a form, and answers 400 or 415. Second, the JSON inside -d is itself wrong — a stray comma, a missing brace — so verify it first with echo '{"book_id": 2}' | jq ., which is faster than sending it and guessing where it broke. Third, wrapping -d in double quotes without escaping the inner double quotes, so the shell shreds your JSON before curl ever sees it. The safe habit is the demo's: single quotes outside, double quotes inside; and once the data gets complicated, switch to -d @order.json and keep the JSON in a file, which is easier on both your eyes and the shell.

Broken JSON: admit it first, then locate it

Section 5 of the demo script deliberately asks for an endpoint that returns truncated JSON:

curl -s http://127.0.0.1:18765/api/broken | jq .
curl -s http://127.0.0.1:18765/api/books | jq -e '.[0].stock > 0'

What it does: the truncated response is {"title": "oops", missing its closing brace, so jq fails to parse it with exit code 5, and the first line of the error is jq: parse error: Unfinished JSON term at EOF at line 1, column 16; the normal book list, checked with jq -e '.[0].stock > 0', exits with 0, meaning the assertion passed. Why it is written this way: Unfinished JSON term at EOF means "the JSON ended before it was finished", and line 1, column 16 is exactly where it broke — the error message already tells you the problem plainly: the response was cut off. The right reaction is not to rewrite the jq filter but to ask why the response was cut off: did the server drop the connection halfway, did a proxy truncate a large response, is the API itself broken? jq -e is a different, handy tool: it turns jq from a "formatting tool" into an "assertion tool" — exit 0 when the expression is true, 1 when it is false — which is exactly what you want in a smoke test script. After every deploy, run a jq -e assertion that the key fields exist and the numbers are sane; it is far more reliable than opening the page and eyeballing it.

There is a sneakier kind of "broken JSON": the response looks like JSON and jq parses it fine, but a field's type is not what you expected. You assumed price was the number 58, but it is the string "58", and your code's addition produces a strange result. jq can expose this at a glance: jq '.[0] | to_entries[] | "\(.key): \(.value | type)"' lists every field's name and type. Asking "what type is this field" one extra time during debugging saves a lot of trouble caused by "I assumed".

One more step: simple statistics with jq

Debugging often means answering "which one is biggest, which one is smallest", and jq answers without a loop. The demo's 4 books sort like this:

jq -r 'sort_by(.price) | .[0] | "\(.title): \(.price)"' books.json
jq -r 'sort_by(.price) | .[-1] | "\(.title): \(.price)"' books.json
jq -r '.[] | "\(.title): price \(.price), stock \(.stock)"' books.json

What it does: sorted by price, the cheapest is "Git in Practice" at 29, the most expensive is "Bash Handbook" at 58, and the last line prints every book as one readable line. (The first two commands print the Chinese titles as returned by the mock; the numbers are 29 and 58.) Why it is written this way: sort_by(.price) sorts by price, .[0] is the first item after sorting, .[-1] is the last, and a negative index in jq counts back from the end. This is a natural debugging move: an API returns dozens of orders and you want the largest amount; it returns a pile of log entries and you want the slowest one; sort first, then take the ends. The third line's "\(.title): price \(.price)" is jq string interpolation, expressions inside braces and plain text outside, and each line it produces can go straight into a debugging note. The principle to keep: any statistic you can understand at a glance is worth computing in the terminal with jq, rather than exporting JSON into a spreadsheet just to look at a number.

Save the failing response: a debugging note must be reproducible

Getting an API to work is not the end of the job, and failing to get it to work is even less so. A common debugging mistake is to look at an error in the terminal, close it, and then be unable to find that response again when you want to double-check it. The right habit is to save every failing response exactly as it arrived. The demo does the same thing it did for the good response:

curl -s http://127.0.0.1:18765/api/books/99 > failed.json
cat failed.json
jq . failed.json

What it does: it saves the 404 response body into failed.json, which contains {"error": "book not found"}. Why: first, you can read it slowly without re-sending the request; second, you can send the file to a colleague or paste it into an issue, and they see exactly what you saw instead of guessing what request you sent; third, you can use it as a regression test — after the fix, send the same request again, compare the old and new files, and confirm the error really changed. One more small habit worth keeping: name failed files with a date, such as failed-2026-11-24.json, so a month later you can still tell when the problem appeared. Debugging is finished not when "it works this time" but when "next time the same problem appears, I can locate it in five minutes". The saved failing response is where that next location starts.

The five most common beginner mistakes

The first mistake is treating curl's exit code as the HTTP status code: curl returns 0 even on a 404, so judge success with -w "%{http_code}" or add --fail. The second is skipping -s: the progress meter mixes into the JSON, jq reports a parse failure, and you blame the server. The third is not wrapping the jq program in single quotes: the dots and brackets in jq .title have special meaning to the shell, which interprets them first, and the error message is baffling. The fourth is extracting a field without -r: the string comes out with quotes, those quotes ride into the next request, the server answers 400, and you think the parameters are wrong. The fifth is assuming a field always exists: the API changes, a field disappears, your jq silently outputs null, and the calculation after it quietly goes wrong. The demo's .stock // 0 idiom defends against this: give a missing field a default rather than letting null travel onward.

Debugging checklist: next time an API fails, follow this order

Step one, send the request once on its own with curl and save the response to a file; do not guess inside application code. Step two, read the status code: 200 means keep reading the body, 404 means check the URL and the id, 401 or 403 means check authentication, 500 means look at the server logs, 429 means stop and wait instead of retrying in a hurry. Step three, read the Content-Type and confirm you received JSON rather than an error page. Step four, pretty-print with jq . and check each field with jq length and jq -r '.field': is it there, is the type right? Step five, write down the smallest reproduction: which curl command, which status code, which error text. With those three things in hand, an AI or a colleague can help immediately instead of spending half an hour reproducing your problem first. Once this flow is familiar, debugging an API stops being guesswork and becomes a craft: every step produces output, every step can be verified, and when something goes wrong you stop at the step where it went wrong and fix it there.

Scope and next steps

One more reminder is worth making: every example in this guide ran against a local mock API, never against any real live service. Practise on a local mock first and only then move to a real API — real APIs have rate limits, some charge per call, and using one for practice wastes money and risks writing test data into production. A local mock can be restarted at any time, its data is fully under your control, and failures can be reproduced; once curl and jq feel natural locally, you will face a real API's surprises with far more confidence.

This guide covers only the curl-plus-jq debugging basics: GET, POST, status codes, field extraction, and recognising broken JSON. Not covered: login and token authentication, OAuth flows, file uploads, WebSockets, and server-side log analysis — those are advanced topics, best learned after this guide's flow is second nature. The suggested next step: write a three-line smoke test script for your project — curl once for a key request, then a jq -e assertion that the status code is 200, the key fields exist, and the numbers are greater than 0, failing loudly on a non-zero exit code. Run it every time you change anything API-related, and the next time an API breaks you will know in the terminal first, instead of hearing it from a user. API debugging skill is not memorised; it is practised by walking the checklist every time something breaks.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles