TExcelTAD
Home › JSON › JSON Server & APIs

JSON Server & APIs

The most important everyday use of JSON is talking to servers. A web API receives requests over HTTP and answers with data — and today that data is almost always JSON. This lesson explains the conversation from both sides.

Note: ExcelTAD runs entirely in your browser without a backend, so the network examples here are shown as non-runnable code. The runnable examples simulate the JSON part of the exchange.

The request/response cycle

  1. The client (browser, mobile app, script) sends an HTTP request, for example GET /api/products/7.
  2. The server looks up the data, converts it to JSON text and sends it back with the header Content-Type: application/json.
  3. The client parses the JSON text and uses the data.

A typical exchange looks like this:

http
GET /api/products/7 HTTP/1.1
Host: shop.example.com
Accept: application/json
http
HTTP/1.1 200 OK
Content-Type: application/json

{"id":7,"name":"Desk Lamp","price":18.5,"inStock":true}

Receiving JSON with fetch()

In the browser, fetch() sends the request and response.json() reads the body and parses it in one step:

js
async function loadProduct(id) {
  const response = await fetch(`https://shop.example.com/api/products/${id}`);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  const product = await response.json();   // = JSON.parse(await response.text())
  console.log(product.name, product.price);
}

Two things can go wrong, and good code handles both: the server can answer with an error status (404, 500…), and the body can be invalid JSON (for example an HTML error page), which makes response.json() reject.

Sending JSON to a server

To send data, stringify it and set the Content-Type header so the server knows how to read the body:

js
const newReview = { productId: 7, stars: 5, text: "Bright and quiet." };

const response = await fetch("https://shop.example.com/api/reviews", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(newReview),
});
const saved = await response.json();
console.log("Created review", saved.id);

Simulating a server

The parts that involve JSON are easy to try without a network. Here a tiny fake "server" function receives a request body as text, parses it, and returns a JSON response string — just like a real backend:

js · try it yourself
const db = [{ id: 1, name: "Desk Lamp", price: 18.5 }];

function handleRequest(method, path, bodyText) {
  try {
    if (method === "GET" && path === "/api/products") {
      return { status: 200, body: JSON.stringify(db) };
    }
    if (method === "POST" && path === "/api/products") {
      const input = JSON.parse(bodyText);
      if (typeof input.name !== "string" || typeof input.price !== "number") {
        return { status: 400, body: JSON.stringify({ error: "name and price are required" }) };
      }
      const product = { id: db.length + 1, name: input.name, price: input.price };
      db.push(product);
      return { status: 201, body: JSON.stringify(product) };
    }
    return { status: 404, body: JSON.stringify({ error: "not found" }) };
  } catch {
    return { status: 400, body: JSON.stringify({ error: "invalid JSON" }) };
  }
}

console.log(handleRequest("POST", "/api/products", '{"name": "Mouse Pad", "price": 6}'));
console.log(handleRequest("POST", "/api/products", '{"name": "Cable"}'));
console.log(handleRequest("POST", "/api/products", "{name: 'oops'}"));
console.log(handleRequest("GET", "/api/products").body);
{ status: 201, body: '{"id":2,"name":"Mouse Pad","price":6}' }
{ status: 400, body: '{"error":"name and price are required"}' }
{ status: 400, body: '{"error":"invalid JSON"}' }
[{"id":1,"name":"Desk Lamp","price":18.5},{"id":2,"name":"Mouse Pad","price":6}]

Designing JSON responses

Good APIs use predictable shapes. A few widely used conventions:

Situation Typical JSON
Single resource {"id": 7, "name": "Desk Lamp"}
List with paging {"data": [...], "page": 2, "totalPages": 9}
Error {"error": {"code": "NOT_FOUND", "message": "No product 99"}}
Created resource status 201 + the new object, including its id
Nothing to return status 204 and no body (don't call .json()!)

A client can handle a paged list like this:

js · try it yourself
const page = JSON.parse(`{
  "data": [
    {"id": 11, "title": "Learn JSON"},
    {"id": 12, "title": "Build an API"}
  ],
  "page": 2,
  "perPage": 2,
  "total": 5
}`);

const totalPages = Math.ceil(page.total / page.perPage);
for (const item of page.data) console.log(`#${item.id} ${item.title}`);
console.log(`Page ${page.page} of ${totalPages}`);
console.log(page.page < totalPages ? `Next: ?page=${page.page + 1}` : "Last page");
#11 Learn JSON
#12 Build an API
Page 2 of 3
Next: ?page=3

Building a JSON API on the server

On a Node.js server the same two functions do the work. This minimal sketch uses only the built-in http module:

js
import http from "node:http";

const products = [{ id: 1, name: "Desk Lamp", price: 18.5 }];

http.createServer((req, res) => {
  if (req.url === "/api/products") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(products));
  } else {
    res.writeHead(404, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: "not found" }));
  }
}).listen(3000);

Frameworks such as Express (res.json(data)), Flask (jsonify(data)) and ASP.NET Core do the stringifying and headers for you.

Mock APIs for practice

While learning, you can create a fake REST API from a JSON file with tools like json-server: a file such as {"posts": [...], "users": [...]} instantly becomes endpoints like /posts and /users/1. Public practice APIs like JSONPlaceholder serve fake data in the same way.

CORS in one paragraph

Browsers only let a page read a response from another origin if that server allows it with an Access-Control-Allow-Origin header. This rule (CORS) is enforced by the browser, not by JSON — but it's the reason a fetch() to someone else's API may fail even though the URL works in a new tab.

Test yourself

Which header tells the receiver that the body is JSON?

  1. Accept: json
  2. Content-Type: application/json
  3. Format: JSON
  4. X-JSON: true

What does await response.json() do?

  1. Sends JSON to the server
  2. Reads the body and parses it as JSON
  3. Checks the HTTP status
  4. Converts an object to a string

Which status code usually means 'created, here is the new resource'?

  1. 200
  2. 201
  3. 204
  4. 404