Fetch API & working with APIs (concept)
Computer Science · JavaScript
Question 1 of 10
0An API endpoint is best described as:
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Fetch API & working with APIs (concept) explained
The fetch function sends an HTTP request from JavaScript and returns a promise for the response. Browser and Node.js code use it to load data from web APIs, usually as JSON.
fetch resolves to a Response object once the response headers arrive. The body is read separately with response.json() or response.text(), which also return promises, so await is commonly used for both steps.
async function getUser(id) {
const response = await fetch("https://api.example.com/users/" + id);
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
}
fetch rejects only when the request cannot be completed, such as a network failure. An HTTP error like 404 still resolves, so check response.ok, which is true for statuses 200 to 299. Requests default to GET; to send data, pass an options object with method "POST", a Content-Type header and a body made with JSON.stringify. Browsers also apply CORS rules, so the server must allow cross-origin requests.
Worked example
Suppose the request for user 42 returns status 404. response.ok is false, so the function throws an Error with the message HTTP 404. With status 200, response.ok would be true and response.json() would return the user.
What you will practise
104 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- fetch() performs:
- fetch() returns:
- A response has:
- res.json():
- Headers carry:
- HTTP status 404 means:
- Status codes in the 200 range indicate:
- Status codes in the 500 range indicate:
…and 96 more.