Node.js Foundations·From script to service

A JSON HTTP API

HTTP is a request, a response and a status code, not a function call.

Intermediate 15 min read Lesson 7 of 300 Challenge included
What you will be able to do
  • Use 201 for created resources and 400 for invalid input.
  • Set content-type: application/json on JSON responses.
  • Limit request body size before reading it into memory.

In plain English

A useful API has predictable methods, content types and status codes. Parse the body with a size limit, validate the shape and return a consistent error format. Never send a stack trace to a client.

api.mjsJavaScript
import { createServer } from 'node:http'

const server = createServer(async (request, response) => {
  if (request.method !== 'POST' || request.url !== '/api/notes') {
    response.writeHead(404, { 'content-type': 'application/json' })
    return response.end(JSON.stringify({ error: 'NOT_FOUND' }))
  }

  let raw = ''
  for await (const chunk of request) raw += chunk
  if (raw.length > 10_000) {
    response.writeHead(413)
    return response.end()
  }

  const body = JSON.parse(raw || '{}')
  if (typeof body.text !== 'string' || body.text.length < 3) {
    response.writeHead(400, { 'content-type': 'application/json' })
    return response.end(JSON.stringify({ error: 'INVALID_INPUT' }))
  }

  response.writeHead(201, { 'content-type': 'application/json' })
  response.end(JSON.stringify({ id: crypto.randomUUID(), text: body.text }))
})
Your turn

Reject invalid notes

Medium

Return 400 when a note is shorter than three characters. Return 201 with an id for a valid note.

JS · starter
const body = { text: 'hi' }
Check your understanding before moving on.
Knowledge checkQuestion 1

Which status code means the request body was too large?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 7 of 300 · 0% of course