🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js A Small CRUD API

CRUD is create, read, update, and delete. Four verbs, one books endpoint, each tested with curl.

Change one book

The PATCH call marks book 4 as read. The answer holds the changed book.

curl -s -X PATCH -H 'Content-Type: application/json' -d '{"read":true}' http://localhost:3112/api/books/4

Delete one book

The DELETE call removes book 4. The answer holds the deleted book.

curl -s -X DELETE http://localhost:3112/api/books/4

Example

curl -s -X POST -H 'Content-Type: application/json' -d '{"title":"The Left Hand of Darkness","author":"Ursula K. Le Guin"}' http://localhost:3112/api/books

Key points

  • CRUD: create, read, update, and delete, the four jobs of a data endpoint
  • GET reads the books. POST creates one.
  • PATCH changes one book. DELETE removes one.
  • A good create answers 201. A good change or delete answers 200.
  • A missing book answers 404, with the words Book not found.
  • Bad data answers 400, with the field errors. Nothing is saved.

In this example, the POST call creates a book. The answer is 201, and the book comes back with id 4 and read false. The id is one more than the highest id in the store. The same call with an empty title answers 400 with the title error, and a PATCH or DELETE for a missing book answers 404 with Book not found. Four verbs, one endpoint, and each answer says what happened.

Note

The same Zod schema checks the POST here and the form in the earlier lessons.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

What status does a good create answer?