Exercises
Objectives
This chapter introduces no new concepts. It’s a chance to practice everything from this module: REST conventions, HTTP methods, authentication, CRUD, and WebSockets.
Exercises 1-4 use the real JSONPlaceholder API and can run in a browser or Node with real network access. Exercises 5-10 are conceptual or need a real server, write the code and reason through it.
Exercises
-
Fetch
https://jsonplaceholder.typicode.com/comments?postId=1and log how many comments come back. Check:5. -
Fetch
https://jsonplaceholder.typicode.com/users/2/albumsand log how many albums come back. Check:10. Explain, in your own words, what this nested-style URL represents. -
Fetch
https://jsonplaceholder.typicode.com/posts/9999(an id that doesn’t exist) and logresponse.statusandresponse.ok. Check:404andfalse. -
Write the
fetch()call for aPATCHrequest tohttps://jsonplaceholder.typicode.com/todos/1that changes onlycompletedtotrue, and log the parsed response. -
Classify each of these status codes by family (
2xx,4xx, or5xx) and explain what each specifically means:201,401,403,500,204. -
Mark each HTTP method as idempotent or not, with a one-sentence reason:
GET,POST,PUT,DELETE. -
Write a
fetch()call to"https://api.example-orders.com/orders"that sends a token stored inlocalStorageunder the key"authToken"as a Bearer token in theAuthorizationheader. -
A request comes back with
status === 401. A different request comes back withstatus === 403. Write what your code should do differently in each case, and explain why. -
Write the code to open a WebSocket connection to
"wss://chat.example-chat.com", log"Connected"once it opens, and log any message received throughonmessage. -
A page needs to show a notification badge with the number of unread messages, updating live as new messages arrive, no reload. Explain, in your own words, whether this is better suited to polling with
fetch()or a WebSocket, and why.
Recap
You can now read a REST URL and predict what it does, choose the right HTTP method for the job, send authentication with a request, build a page with full CRUD against a real resource, and explain when a WebSocket beats plain fetch(). That’s the full toolkit for talking to a server.
Next lesson: this module’s mini project, a Weather Dashboard that puts fetch, DOM updates, and a real API together.