Interview Questions: Working with APIs & JSON
API and JSON questions come up in almost every backend or full-stack interview, because consuming a third-party API is one of the most universal day-to-day tasks in professional software work. This set covers requests.get() and the Response object, status codes, json.loads()/json.dumps(), navigating nested JSON, the two genuinely different request failure modes, .get() for missing keys, query params vs. headers, why API keys must never be hardcoded, and the fetch-parse-format pipeline that almost every real API-consuming program follows.
1 What does requests.get(url) actually return, and what are its three most commonly used attributes?
requests.get(url) sends an HTTP request to url and returns a Response object describing what came back — it does not return the data itself directly. The three attributes used constantly: response.status_code, a 3-digit number reporting success or failure; response.text, the raw response body as a plain string, regardless of what format it's actually in; and response.json(), a method (not an attribute) that parses .text as JSON and returns ready-to-use Python data, but only if the body genuinely is valid JSON. A common beginner assumption is that requests.get() itself returns the data — it returns the whole response wrapper, and getting the actual data is a second, separate step.
Saying requests.get(url) returns a dict directly, or not knowing the difference between .text and .json().
"If a server returns a 404 page written in plain HTML, what happens if .json() is called on that response anyway?" (It raises an error, since the body isn't valid JSON — which is exactly why real code checks .status_code before ever calling .json().)
2 What do the status code ranges 2xx, 4xx, and 5xx each mean?
The ranges matter more than any individual number. 2xx means success — the request was understood and handled as expected (200 OK is the most common). 4xx means the request itself had a problem — a bad URL, missing authentication, a malformed parameter — the fault is on the caller's side (404 Not Found, 401 Unauthorized). 5xx means the request was perfectly fine, but the server broke while trying to handle it — the fault is on the server's side (500 Internal Server Error). Distinguishing 4xx from 5xx matters practically: a 4xx usually means the calling code needs to change something about the request, while a 5xx usually means retrying later (or reporting the outage) is the more sensible response.
Treating every non-200 code the same way, or not knowing which range means a client-side mistake versus a server-side one.
Follow-up"Does getting a 500 status code usually mean the request itself was malformed?" (No — a 500 specifically means the server accepted a valid-looking request but failed internally while processing it; the request format itself wasn't the problem.)
3 What's the difference between json.loads() and json.dumps()?
They go in opposite directions. json.loads(text) ("load string") parses a JSON string into real Python data — dicts, lists, strings, numbers, booleans, None. json.dumps(data) ("dump string") does the reverse: converts Python data into a JSON string. A useful memory aid: data coming in from an API response needs loads(); data going out to be sent, saved, or printed readably needs dumps(), optionally with indent=2 for human-readable formatting. Both functions handle the type translation automatically in both directions — JSON's true/false/null become Python's True/False/None, and back again.
Mixing up which function goes which direction, or not knowing that a Response object's .json() method is essentially calling json.loads() on .text automatically.
"If data = json.loads('{\"active\": true}'), what type is data[\"active\"] in Python?" (bool — specifically True; JSON's lowercase true is automatically converted to Python's capitalized True during parsing.)
4 Why does json.dumps(data, indent=2) matter, and when should it not be used?
indent=2 reformats the exact same JSON data across multiple lines with consistent indentation, purely for human readability — it adds newlines and whitespace, no new information. It's genuinely useful when printing JSON to a terminal for debugging, writing it to a log file a person will read later, or inspecting an unfamiliar API response's shape for the first time. It should specifically not be used when actually sending JSON over a network connection (as the body of a real API request, for instance) — the extra whitespace adds bytes to every request with zero benefit, since nothing on the receiving end needs to visually read it before parsing it back with json.loads().
Treating indent= as changing the underlying data in any way, or not being able to name a case where it's actively the wrong choice.
"Does json.dumps({\"a\": 1}, indent=2) == json.dumps({\"a\": 1}) evaluate to True or False?" (False — they're different strings, since one has extra whitespace/newlines the other doesn't; but json.loads() on either one recovers the identical underlying data, since the difference is purely cosmetic.)
5 How would you read a value three levels deep in a nested JSON response, like {"a": {"b": {"c": 42}}}?
By chaining ordinary [key] lookups, one level at a time, in the order the nesting goes: data["a"]["b"]["c"]. Nothing special is needed for depth — each [key] simply returns whatever value is stored there, and if that value happens to be another dict (or list), the next [key]/[index] in the chain operates on that. The practical skill isn't a special syntax; it's reading the actual shape of a real response first (often by pretty-printing a sample with json.dumps(data, indent=2)) so the chain of lookups matches the real structure, rather than guessing blindly.
Assuming there's a special "deep get" syntax or method built into core Python for this (there isn't — it's plain chained indexing), or not being able to read an unfamiliar nested structure's shape before writing navigation code.
Follow-up"Given data = {\"users\": [{\"name\": \"Kai\"}, {\"name\": \"Lee\"}]}, how would you get \"Lee\"?" (data[\"users\"][1][\"name\"] — first reach the list with [\"users\"], then its second item with [1], then that dict's \"name\" key.)
6 What are the two genuinely different ways a real API request can fail, and how does handling differ between them?
The first is a network-level failure: the request never even completes — no internet connection, a timeout, an unreachable host, a malformed URL. This is caught with try/except requests.exceptions.RequestException, and there's no status code to check at all, because no response ever came back. The second is a bad status code on a completed response: the network call succeeded (a response genuinely arrived), but that response reports a problem — a 404, a 500 — checked with if response.status_code != 200: or the response.raise_for_status() shortcut. Treating both as one single category misses real cases: code that only catches exceptions will crash (or silently mishandle) a perfectly well-formed error response, and code that only checks status codes will crash outright the moment the network itself fails, since there's no response object at all to check a status on.
Treating "the request failed" as one single case, or assuming a try/except around requests.get() alone is sufficient without also checking the status code on a successful call.
"If requests.get(url) completes with no exception at all, but the server is down for maintenance and returns a 503, would a bare try/except requests.exceptions.RequestException catch that on its own?" (No — the request completed successfully at the network level, so no exception is raised; a 503 is only caught by checking response.status_code, or using raise_for_status(), separately from the exception handling.)
7 When should .get(key, default) be used instead of a plain [key] lookup on a parsed API response?
.get(key, default) should be used for any field that is genuinely optional in the API's response — a field that might legitimately be absent depending on the data, not because something has gone wrong. A plain [key] lookup is still the right choice for a field the API's documentation guarantees will always be present; if that field is ever actually missing, letting [key] raise a loud KeyError is more honest than silently treating a required field as optional and papering over what is, in that case, a genuine data problem worth noticing. The distinction to hold onto: .get() is for expected absence, not for hiding unexpected absence.
Reflexively using .get() everywhere "just in case," which can silently mask a real bug when a required field goes missing, or never using .get() at all and crashing on every optional field's absence.
"If an API's documentation guarantees a response always includes an \"id\" field, and that field is somehow missing on a real call, is silently returning a default via .get(\"id\", None) the right call?" (Arguably not — if a documented, required field is missing, that's a sign something is genuinely wrong with the response, and a loud failure (or explicit logging) is often more useful than quietly proceeding with a placeholder value.)
8 What's the difference between a query parameter and a header, and when is each one used?
A query parameter customizes what is being requested — it's part of the URL itself, appended after a ? (?city=Austin&units=imperial), and is used for things like a search term, a city, a page number, or a sort order. A header carries information about the request itself, sent separately from the URL — most commonly used for authentication (an API key) or content negotiation (what response format is acceptable). requests.get(url, params={...}) builds the query string automatically from a dict; requests.get(url, headers={...}) attaches headers separately. Mixing the two up matters practically: an API key sent as a query parameter can end up logged in plain text in a server's access logs (URLs are commonly logged, headers usually aren't as visibly), which is one reason authentication almost always goes in a header instead.
Not knowing that query parameters end up as part of the visible URL (and can end up in logs, browser history, etc.), or treating params and headers as interchangeable.
Follow-up"Would sending an API key as params={\"api_key\": \"...\"} instead of a header have any practical downside?" (Yes — it becomes part of the visible URL, which is far more likely to end up logged somewhere (server access logs, browser history, shared links) than a header value, making it a less safe place for a secret.)
9 Why should a real API key never be hardcoded directly into source code, even in a private repository?
Because a hardcoded key becomes part of that file's committed history — if the repository is ever made public, transferred, forked, or if the commit history is ever exposed in any way, the key is visible in every commit that ever included it, even if a later commit removes it. For a genuinely public repository, this risk is immediate: automated bots specifically scan public repos for exposed API keys within minutes of a push, and a compromised key can rack up usage charges or be used to impersonate whoever owns it. The fix is to read the key from an environment variable at runtime, via os.environ.get(\"API_KEY\"), so the key itself never appears in any file that gets committed at all — it lives only in the environment of whatever machine is running the code, set up separately from the source.
Believing a "private" repository is a safe place for a hardcoded secret (repos can be made public, forked, or leaked), or not knowing the environment-variable pattern as the standard alternative.
Follow-up"If a hardcoded API key is committed and then removed in a later commit, is the key still exposed?" (Yes — the key is visible in the earlier commit's history forever, unless the entire git history is rewritten and force-pushed, which doesn't help if the repo has already been cloned, forked, or scanned by then; the safe fix is never committing it in the first place.)
10 What is the fetch-parse-format pipeline, and why is splitting a program into those three separate steps useful?
It's the repeatable three-stage shape almost every API-consuming program follows: fetch (get the raw response, real or mocked), parse (turn that raw text into usable Python data, pulling out the specific fields needed and handling anything malformed or missing along the way), and format (turn that parsed data into a human-readable result). Splitting these into separate functions means each one can be understood, tested, and changed independently — the parse function never needs to know or care whether its input string came from a real network call or a hand-written test string, and the format function never needs to know anything about HTTP, JSON, or networking at all. The fetch function ends up being the only piece that would ever need to change if the data source itself changed (a different API, a mocked response instead of a real one) — everything downstream of it stays identical either way.
Red flagsWriting one large function that fetches, parses, and formats all in one block, making it impossible to test the parsing logic without also making a real network call.
Follow-up"If a parse function is written to accept a raw JSON string (rather than calling requests.get() itself), can it be tested with a hand-written mock string with no network access at all?" (Yes — that's precisely the benefit of the separation; the parse function only cares that it received a string of JSON text, never where that text came from.)
11 Why does this course (and this chapter specifically) avoid making real network calls in its graded exercises, and is that a realistic way to learn the material?
A live API can go offline, change its response shape, enforce a rate limit, or require a key that expires or costs money — none of which makes for a reliable, reproducible lesson that still works correctly years later for anyone reading it. Using a mocked response (a hardcoded JSON string standing in for "what the API would return") sidesteps all of that while teaching the exact same mechanics: parsing the same shape of JSON, navigating the same nested structure, handling the same kinds of missing fields and bad statuses — the only thing that changes between a mocked example and a real one is where the raw text originally came from, which the fetch-parse-format split (Question 10) deliberately isolates into one small, swappable piece. This is also precisely the same technique used to unit-test real production code that calls APIs, so it's not just a teaching shortcut — it's the actual professional pattern for testing this kind of code without hitting a real network on every test run.
Red flagsAssuming mocked-response practice is somehow "not the real thing" or a lesser substitute, rather than recognizing it as the same technique real test suites use.
Follow-up"If code correctly parses a hand-written mock JSON string matching a real API's documented response shape, will that same code correctly parse the real API's actual response?" (Yes, as long as the mock accurately reflects the real shape — json.loads()/dict navigation behave identically regardless of where the string originated.)
12 What happens if json.loads() is called on text that isn't actually valid JSON?
It raises a json.JSONDecodeError — a missing comma, an unquoted key, a trailing comma, or text that's simply a different format entirely (like an HTML error page) all trigger this. This matters in real API code because a status code of 200 doesn't strictly guarantee the body is valid JSON in every conceivable edge case — a misconfigured server could return a 200 with an HTML body, for instance. Defensive real-world code sometimes wraps response.json() (or json.loads() directly) in its own try/except json.JSONDecodeError, on top of the status-code check, for exactly this rarer but real edge case.
Assuming a successful status code guarantees a parseable JSON body in every case, or not knowing what exception invalid JSON actually raises.
Follow-up"Does a 200 status code alone guarantee response.json() will succeed without raising an error?" (Not with absolute certainty — it's true the overwhelming majority of the time for a well-behaved API, but a malformed or unexpected body can still cause json.JSONDecodeError even on a 200 response, which is why some production code checks for it explicitly.)
13 What's the difference between json.loads()/json.dumps() and json.load()/json.dump() (without the trailing "s")?
They do the identical conversion job, but work with different sources/destinations. json.loads()/json.dumps() (with the "s", for "string") work with a JSON string already sitting in memory — exactly the case for an API response, which arrives as a string. json.load()/json.dump() (no "s") work directly with an already-open file object instead, combining "read/write the file" and "parse/serialize the JSON" into one call — useful for a local config.json file opened with with open(...) as f:, rather than a network response. Using the wrong pair for the situation (e.g. trying to call json.load() on a plain string instead of a file object) raises an AttributeError, since a plain string doesn't have the .read() method json.load() expects to call internally.
Treating the "s" as a stylistic difference rather than a meaningful one (string vs. file object), or trying to call json.load() directly on a string.
"Would json.load(response.text) work correctly on a real Response object?" (No — response.text is a plain string, not an open file object, so json.load() is the wrong function here; json.loads(response.text), or simply response.json(), is correct.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.