Example result: Build a REST API endpoint with validation
AI-generated example · Build · API
Updated

Build a REST API endpoint with validation

This prompt builds one API endpoint properly: validated input, the right status codes, one error format and no internal details leaked. It also handles two requests arriving at once and includes tests.

text-code-rest-api-endpoint — claude — 85 words

Act as a senior backend developer using [STACK, e.g. Node.js with Express and Zod].

Endpoint: [METHOD AND PATH, e.g. POST /api/bookings]
What it does: [e.g. creates a booking if the slot is free]
Input fields and rules: [LIST]
Data store: [e.g. Postgres with Prisma]

Write the route with input validation, clear status codes, error responses in one consistent shape, and no internal details leaked to the client. Handle the case where two requests arrive at once. Include two example requests with curl and two tests.

Ask for the error format you already use in your app, so every endpoint answers in the same shape.

Get a better result

What you will get

A route with input validation, clear status codes, one consistent error shape, no internal details sent to the client, handling for two requests at once, two curl examples and two tests.

Why it works

The input rules and data store lines give the model everything it needs to write real validation and queries instead of placeholders. The line about two requests arriving at once is the one that catches double bookings and double payments, which happy path code misses. Asking for curl examples and tests means you can check it works in a minute.

Common mistake

Two bookings for the same slot can both succeed.

Fix: Ask for a database level guard, such as a unique constraint or a transaction with a lock, not only a check in code.

Also watch for
  • Validation errors return a 500. Ask for 400 or 422 with the field that failed, and keep 500 for real server faults only.
  • The error response includes a stack trace. Ask it to log the full error on the server and send the client only a code and a short message.
Try a variation: add an update endpoint

Ask for the matching PATCH route, with rules for which fields can change and what happens if the booking was already cancelled.

Still not right? Reply with this

Use this exact error format, which the rest of my app already uses: [PASTE FORMAT]. Update the route and the tests.

More chat & writing prompts

See all 465 →