CodingNic

Web APIs and Backend Communication

Exercises

Web APIs and Backend Communication 35 min read

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

  1. Fetch https://jsonplaceholder.typicode.com/comments?postId=1 and log how many comments come back. Check: 5.

  2. Fetch https://jsonplaceholder.typicode.com/users/2/albums and log how many albums come back. Check: 10. Explain, in your own words, what this nested-style URL represents.

  3. Fetch https://jsonplaceholder.typicode.com/posts/9999 (an id that doesn’t exist) and log response.status and response.ok. Check: 404 and false.

  4. Write the fetch() call for a PATCH request to https://jsonplaceholder.typicode.com/todos/1 that changes only completed to true, and log the parsed response.

  5. Classify each of these status codes by family (2xx, 4xx, or 5xx) and explain what each specifically means: 201, 401, 403, 500, 204.

  6. Mark each HTTP method as idempotent or not, with a one-sentence reason: GET, POST, PUT, DELETE.

  7. Write a fetch() call to "https://api.example-orders.com/orders" that sends a token stored in localStorage under the key "authToken" as a Bearer token in the Authorization header.

  8. A request comes back with status === 401. A different request comes back with status === 403. Write what your code should do differently in each case, and explain why.

  9. Write the code to open a WebSocket connection to "wss://chat.example-chat.com", log "Connected" once it opens, and log any message received through onmessage.

  10. 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.