30 Claude Prompts That Build APIs
Describe the endpoint and Claude returns real, ready-to-run code or a valid OpenAPI spec: REST CRUD handlers, JWT and OAuth auth, webhook receivers, rate limiters, validation, and docs. Not "explain how APIs work."
In short: This page contains 30 copy-paste ready prompts, organized into 6 categories with a description and pro tip for each. The first 15 prompts are free instantly โ no signup needed. Hand-curated and tested by the AI Academy team.
REST Endpoints & CRUD
5 promptsExpress CRUD Resource Router
1/30You are a senior Node.js backend engineer. <context> I need a complete, production-ready CRUD router for a single REST resource, returned as one self-contained, well-commented code block I can drop into my Express app. </context> <inputs> - Resource name and fields: [E.G. "task": title, status, dueDate, assigneeId] - Framework/version: [EXPRESS 4 / EXPRESS 5] - Data layer: [PRISMA / KNEX / RAW PG / IN-MEMORY] - ID scheme: [UUID / AUTOINCREMENT] - Auth assumption: [req.user EXISTS / NONE] </inputs> <task> Build a router with GET list (paginated), GET one, POST create, PATCH update, and DELETE, each wired to the data layer. Include input validation, correct status codes (200/201/204/400/404), a 404 for missing rows, async error forwarding to next(err), and JSDoc on every handler. </task> <constraints> - One valid file, no placeholders left unimplemented; async/await with try/catch or an asyncHandler wrapper. - RESTful routes, plural resource path, and JSON responses with a consistent shape. - No secrets or hardcoded connection strings. </constraints> <format> Return the full router as a code block, then a short note on how to mount it and swap the data layer. </format>
Generates a full Express CRUD router for one resource with validation and correct status codes, ready to use.
Pro tip: Tell Claude your exact ORM and it will emit the real query calls instead of pseudo-code you have to translate.
FastAPI CRUD Router with Pydantic
2/30You are a senior Python API engineer who writes idiomatic FastAPI. <context> I need a complete CRUD router for one resource using FastAPI and Pydantic v2, returned as one self-contained, commented code block. </context> <inputs> - Resource and fields (with types): [E.G. "invoice": amount: Decimal, currency: str, status: enum] - Persistence: [SQLALCHEMY 2.0 / TORTOISE / IN-MEMORY DICT] - ID type: [UUID / INT] - Response style: [FULL OBJECT / MINIMAL] </inputs> <task> Build an APIRouter with list (with limit/offset), retrieve, create, update (partial), and delete endpoints. Define separate Create, Update, and Read Pydantic schemas, use response_model on each route, raise HTTPException with proper status codes, and add tags plus summaries so it shows up cleanly in the auto docs. </task> <constraints> - Pydantic v2 syntax (model_config, field validators where useful); valid, runnable Python. - Enums for constrained fields; 404 when a row is missing; 422 handled by FastAPI validation. - No business logic left as TODO. </constraints> <format> Return the full router plus the schema classes as a code block, then note how to include it in the app and where the Swagger UI appears. </format>
Produces a FastAPI CRUD router with typed Pydantic schemas and auto-doc metadata, ready to run.
Pro tip: Give the field types precisely (Decimal, datetime, Literal) so Claude generates strict schemas instead of loose str fields.
Next.js Route Handlers (REST Resource)
3/30You are a full-stack engineer expert in the Next.js App Router. <context> I need REST route handlers for one resource in a Next.js 14+ App Router project, returned as self-contained files with the exact file paths as comments. </context> <inputs> - Resource and fields: [DESCRIBE] - Data access: [PRISMA / DRIZZLE / FETCH TO EXTERNAL API] - Runtime: [NODE / EDGE] - Auth: [NEXTAUTH SESSION / NONE] </inputs> <task> Build app/api/[resource]/route.ts (GET list, POST create) and app/api/[resource]/[id]/route.ts (GET, PATCH, DELETE) using the Web Request/Response and NextResponse.json. Parse and validate the body, return typed JSON, use correct status codes, and handle not-found and validation errors cleanly. </task> <constraints> - TypeScript, valid App Router handler signatures; export the correct HTTP method functions. - Set the runtime export where relevant; no client code, no default exports. - Consistent JSON error shape { error: { code, message } }. </constraints> <format> Return each file as its own code block labeled with its path, then a one-line note on testing with curl. </format>
Builds typed Next.js App Router REST handlers for a resource across the correct file paths, ready to use.
Pro tip: Ask Claude to also emit a shared lib/validation.ts so both route files import the same schema instead of duplicating it.
Paginated, Filterable, Sortable List Endpoint
4/30You are a backend engineer who designs clean list APIs. <context> I need a single GET list endpoint that supports pagination, filtering, and sorting via query params, returned as one commented code block plus the query it builds. </context> <inputs> - Framework/language: [EXPRESS + PRISMA / FASTAPI + SQLALCHEMY / OTHER] - Resource and filterable fields: [E.G. orders: status, customerId, createdAt range] - Sortable fields: [LIST] - Pagination style: [OFFSET/LIMIT / CURSOR] </inputs> <task> Build the endpoint: parse page/pageSize (or cursor), whitelist filter and sort fields, reject unknown sort keys, build a safe parameterized query, and return { data, pagination } with total count, page info, and next cursor where applicable. Guard against unbounded page sizes with a hard max. </task> <constraints> - Parameterized queries only (no string interpolation); whitelist all sortable/filterable columns. - Sensible defaults and a documented max pageSize; stable sort with a tiebreaker on id. - Valid, runnable code with comments explaining the safety choices. </constraints> <format> Return the endpoint as a code block, then a table of every supported query param with type, default, and an example. </format>
Generates a safe paginated/filterable/sortable list endpoint with a documented query-param contract, ready to use.
Pro tip: Ask for cursor pagination if your data changes often; it avoids the page-drift bug that offset pagination has under inserts.
Multipart File Upload Endpoint
5/30You are a backend engineer who handles file uploads securely. <context> I need a file upload endpoint that accepts multipart/form-data, validates the file, and stores it, returned as one self-contained, commented code block. </context> <inputs> - Stack: [EXPRESS + MULTER / FASTAPI UploadFile / NEXT ROUTE HANDLER] - Allowed types and max size: [E.G. PNG/JPG/PDF, 10 MB] - Storage target: [LOCAL DISK / S3 / SUPABASE] - Return value: [PUBLIC URL / FILE ID] </inputs> <task> Build the upload handler: parse the multipart body, enforce the size limit and an allowlist of MIME types (checked against magic bytes, not just the extension), generate a collision-safe filename, stream to storage, and return the file metadata as JSON. Return 413 for too-large and 415 for unsupported type. </task> <constraints> - Validate real content type, not just the client-supplied name; never trust the original filename for the storage path. - Stream rather than buffer whole files where the stack allows; clean up on failure. - Valid, runnable code with comments on each security check. </constraints> <format> Return the handler as a code block, then a curl example that uploads a file and the exact error responses for oversized and wrong-type files. </format>
Builds a secure multipart upload endpoint with type and size validation and storage wiring, ready to use.
Pro tip: Tell Claude to verify magic bytes; extension-only checks are trivially bypassed by renaming a malicious file.
XML tags are just the start. Learn the full Claude workflow.
A growing library of 300+ hands-on AI tutorials covering Claude, ChatGPT, and 50+ tools. New tutorials added every week.
Webhooks
5 promptsWebhook Receiver with HMAC Verification
11/30You are a backend engineer who integrates third-party webhooks safely. <context> I need an endpoint that receives webhooks and verifies their signature before trusting the payload, returned as one self-contained, commented code block. </context> <inputs> - Provider or signature scheme: [E.G. STRIPE, GITHUB, SVIX, or CUSTOM HMAC-SHA256] - Stack: [EXPRESS / FASTAPI / NEXT ROUTE HANDLER] - Events I care about: [LIST] - What to do on a valid event: [ENQUEUE JOB / UPDATE DB] </inputs> <task> Build the receiver: read the RAW request body (before JSON parsing), compute the expected signature from the shared secret and any timestamp, compare in constant time, reject stale timestamps to block replay, and only then parse and dispatch on event type. Return 2xx fast; do heavy work asynchronously. Return 400 on bad signature. </task> <constraints> - Use the raw, unparsed body for signature verification; constant-time compare; enforce a timestamp tolerance window. - Acknowledge quickly (2xx) and offload processing; never do slow work inline. - Valid, runnable code, including the framework-specific way to access the raw body. </constraints> <format> Return the endpoint as a code block, then note how to get the raw body in this framework and how to test with a signed sample. </format>
Builds a signature-verified webhook receiver with replay protection and fast acknowledgement, ready to use.
Pro tip: The #1 bug is verifying against the parsed body; tell Claude your framework so it wires up raw-body access correctly.
Webhook Sender with Retries + Backoff
12/30You are a backend engineer building an outbound webhook delivery system. <context> I need a reliable webhook sender that signs payloads and retries with exponential backoff, returned as one self-contained, commented code block. </context> <inputs> - Stack and queue: [NODE + BULLMQ / PYTHON + CELERY / SIMPLE IN-PROCESS] - Signing scheme: [HMAC-SHA256 HEADER NAME] - Retry policy: [E.G. 5 ATTEMPTS, BACKOFF 1s..1h] - Success criteria: [2xx WITHIN 10s] </inputs> <task> Build a deliverWebhook function that POSTs the JSON payload with a signature header, an event id, and a timestamp; treats non-2xx or timeout as failure; schedules retries with exponential backoff plus jitter; caps attempts; and moves exhausted deliveries to a dead-letter store. Include the delivery-attempt record model. </task> <constraints> - Sign every payload; include a unique event id so receivers can dedupe. - Exponential backoff WITH jitter; a per-request timeout; a hard attempt cap into a dead-letter queue. - Valid, runnable code with comments on the backoff math. </constraints> <format> Return the sender plus the delivery-record model as a code block, then a table of the retry schedule (attempt, delay). </format>
Generates a signed outbound webhook sender with jittered exponential-backoff retries and dead-lettering, ready to use.
Pro tip: Ask for jitter explicitly; without it, all your failed deliveries retry in lockstep and hammer the receiver at once.
Idempotent Webhook Processing
13/30You are a backend engineer who makes event handlers safe against duplicates. <context> Providers redeliver webhooks, so my handler must process each event exactly once. I need idempotent processing, returned as one self-contained, commented code block. </context> <inputs> - Stack and store: [EXPRESS + POSTGRES / FASTAPI + REDIS] - Event id source: [PROVIDER'S EVENT ID HEADER/FIELD] - The side effect to protect: [E.G. GRANT ACCESS, CHARGE, EMAIL] - Retention for processed ids: [E.G. 30 DAYS] </inputs> <task> Build a processEvent wrapper that records each event id in a processed-events table/set within the SAME transaction as the side effect, so a redelivery is detected and skipped. Handle the race where two deliveries arrive concurrently (unique constraint / SETNX). Return 200 for both first-time and duplicate deliveries so the provider stops retrying. </task> <constraints> - Dedupe key = provider event id; the dedupe write and the side effect must be atomic (one transaction or a lock). - Handle concurrent duplicates via a unique constraint or atomic set op, not a check-then-write gap. - Valid, runnable code with the processed-events schema and a comment on the concurrency guarantee. </constraints> <format> Return the wrapper plus the schema as a code block, then explain why a naive "SELECT then INSERT" is not safe here. </format>
Builds atomic idempotent webhook processing that survives redeliveries and concurrent duplicates, ready to use.
Pro tip: Insist the dedupe record and the side effect share one transaction; separate writes leave a window where you double-process.
Webhook Subscription Management API
14/30You are a platform engineer letting customers manage their own webhook endpoints. <context> I need CRUD endpoints so customers can register, list, update, and delete webhook subscriptions, returned as one self-contained, commented code block. </context> <inputs> - Stack and DB: [DESCRIBE] - Event types customers can subscribe to: [LIST] - Per-subscription secret: [AUTO-GENERATED / CUSTOMER-PROVIDED] - Tenancy: [SCOPED TO req.user / API KEY OWNER] </inputs> <task> Build endpoints to create a subscription (validate the target URL is https and not a private/internal address, generate a signing secret, return it once), list the caller's subscriptions, update the URL/events/active flag, and delete one. Add a POST /:id/test that sends a sample signed event so customers can verify their receiver. </task> <constraints> - Reject non-https and SSRF-risky targets (localhost, link-local, private ranges); scope every query to the authenticated owner. - Show the signing secret only on creation; store it hashed or encrypted. - Valid, runnable code with the subscription schema and comments on the SSRF checks. </constraints> <format> Return the endpoints plus the schema as a code block, then note the event types and the test-delivery behavior. </format>
Generates a customer-facing webhook subscription CRUD API with SSRF-safe URL validation and a test endpoint, ready to use.
Pro tip: Have Claude add the SSRF allowlist check now; a webhook target field is a classic way for attackers to probe your internal network.
Event Replay & Dead-Letter Endpoint
15/30You are a backend engineer building operational tooling for webhook reliability. <context> I need admin endpoints to inspect failed webhook deliveries and replay them, returned as one self-contained, commented code block. </context> <inputs> - Stack and store: [DESCRIBE] - Delivery record fields: [id, event, target, attempts, lastStatus, payload, ...] - Who can access: [ADMIN ROLE / INTERNAL ONLY] - Replay behavior: [SINGLE / BULK BY FILTER] </inputs> <task> Build GET /deliveries (filter by status, event type, date range, with pagination), GET /deliveries/:id (full payload + attempt history), POST /deliveries/:id/replay (re-enqueue a single delivery), and POST /deliveries/replay (bulk replay matching a filter, with a dry-run count first). Guard all of it behind admin auth. </task> <constraints> - Admin-only; bulk replay must support a dry-run that returns the count before actually re-enqueuing. - Replays reuse the original event id so downstream idempotency still holds; never mutate the stored payload. - Valid, runnable code with comments on the dry-run and idempotency interplay. </constraints> <format> Return the endpoints as a code block, then a short runbook: how to find a failed delivery and safely replay it. </format>
Builds admin replay and dead-letter inspection endpoints with dry-run bulk replay, ready to use.
Pro tip: Always dry-run bulk replays first; ask Claude to make the count endpoint mandatory before any mass re-enqueue.
Rate Limiting & Caching
5 promptsToken-Bucket Rate Limiter (Redis)
16/30You are a backend engineer implementing distributed rate limiting. <context> I need token-bucket rate limiting backed by Redis so it works across multiple app instances, returned as one self-contained, commented code block. </context> <inputs> - Stack and Redis client: [EXPRESS + IOREDIS / FASTAPI + REDIS-PY] - Limit key: [PER API KEY / PER IP / PER USER] - Rate: [E.G. 100 REQUESTS PER MINUTE, BURST 20] - Scope: [GLOBAL / PER ENDPOINT] </inputs> <task> Build middleware that runs a Redis Lua script implementing the token-bucket algorithm atomically (refill by elapsed time, consume one token, return allowed + remaining). Set X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers on every response, and return 429 with a Retry-After header when the bucket is empty. </task> <constraints> - The check-and-decrement must be atomic (Lua script or equivalent) to avoid race conditions across instances. - Emit standard rate-limit headers and Retry-After; fail OPEN or CLOSED explicitly (state which and why) if Redis is down. - Valid, runnable code including the Lua script with comments. </constraints> <format> Return the middleware plus the Lua script as a code block, then explain the atomicity guarantee and the fail-open/closed choice. </format>
Generates an atomic Redis token-bucket rate limiter with standard headers and 429 handling, ready to use.
Pro tip: Ask Claude which way it fails when Redis is unreachable; for a paid API you usually want fail-closed, for a free one fail-open.
Sliding-Window Rate Limiter
17/30You are a backend engineer who needs smoother rate limiting than fixed windows. <context> Fixed windows let bursts double the limit at boundaries. I need a sliding-window (log or weighted) rate limiter, returned as one self-contained, commented code block. </context> <inputs> - Stack and store: [REDIS / IN-MEMORY] - Algorithm preference: [SLIDING WINDOW LOG / SLIDING WINDOW COUNTER] - Rate and window: [E.G. 60 REQUESTS PER 60s] - Key: [IP / USER / KEY] </inputs> <task> Build the limiter implementing the chosen sliding-window algorithm: for the log variant, store request timestamps in a sorted set, trim entries outside the window, count, and add the new one atomically; for the counter variant, blend the current and previous window counts by elapsed fraction. Return allowed + remaining + reset and set 429 with Retry-After when exceeded. </task> <constraints> - Explain the boundary-burst problem the sliding window fixes in a comment. - Atomic operations only; bound memory (trim old entries / expire keys). - Valid, runnable code with the standard rate-limit response headers. </constraints> <format> Return the limiter as a code block, then contrast its accuracy and memory cost against the token-bucket approach in 3-4 lines. </format>
Builds a sliding-window rate limiter that avoids fixed-window boundary bursts, ready to use.
Pro tip: Pick the counter variant if memory matters; it approximates the log with a single number per window instead of every timestamp.
HTTP Caching with ETag & Conditional Requests
18/30You are a backend engineer optimizing API response caching at the HTTP layer. <context> I want clients and proxies to cache my GET responses correctly using ETags and conditional requests, returned as one self-contained, commented code block. </context> <inputs> - Stack: [EXPRESS / FASTAPI] - Resource being served: [DESCRIBE] - Freshness policy: [E.G. PRIVATE, max-age 60, must-revalidate] - ETag basis: [CONTENT HASH / updatedAt VERSION] </inputs> <task> Build a GET handler that computes a strong or weak ETag, sets Cache-Control and Last-Modified, and honors If-None-Match / If-Modified-Since by returning 304 Not Modified with no body when the client's copy is current. Do the same for a mutation returning 412 on a failed If-Match (optimistic concurrency). </task> <constraints> - Correct 304 (empty body, ETag preserved) and 412 semantics; choose strong vs weak ETag and justify it. - Cache-Control directives must match the data's real freshness (no caching private data as public). - Valid, runnable code with comments on each header's effect. </constraints> <format> Return the handler as a code block, then a curl sequence showing a 200 then a 304 on the second request. </format>
Generates ETag-based conditional GET/If-Match handling with correct 304/412 responses, ready to use.
Pro tip: Base the ETag on updatedAt+id when hashing the body is expensive; it is cheaper and still changes on every write.
Redis Cache-Aside Wrapper for Endpoints
19/30You are a backend engineer adding a caching layer to slow read endpoints. <context> I need a reusable cache-aside helper that wraps expensive reads with Redis, handling misses, TTLs, and invalidation, returned as one self-contained, commented code block. </context> <inputs> - Stack and Redis client: [DESCRIBE] - Endpoints to cache: [E.G. GET /products/:id, GET /reports/summary] - TTL and staleness tolerance: [E.G. 300s] - Invalidation triggers: [ON WRITE TO RESOURCE X] </inputs> <task> Build a cached(key, ttl, fetchFn) helper: on hit, return parsed value; on miss, call fetchFn, store the result, and return it. Add namespaced key builders, a delPattern invalidation helper called from write paths, and single-flight/lock to prevent a cache stampede when many requests miss the same key at once. Show it wrapping one read endpoint and being invalidated by its write. </task> <constraints> - Prevent stampede (lock or single-flight) on hot-key misses; jitter TTLs to avoid synchronized expiry. - Never cache errors or partial results; namespace keys so invalidation is targeted. - Valid, runnable code with comments on the stampede protection. </constraints> <format> Return the helper plus a wrapped endpoint and its invalidation as a code block, then note what should never be cached. </format>
Builds a reusable Redis cache-aside wrapper with stampede protection and targeted invalidation, ready to use.
Pro tip: Add TTL jitter; identical TTLs make thousands of keys expire in the same second and all miss at once (a thundering herd).
Per-Key Quota & Usage Tracking
20/30You are a backend engineer building metered API usage for a paid product. <context> I need per-API-key monthly quotas with usage counting and quota-exceeded responses, returned as one self-contained, commented code block. </context> <inputs> - Stack and store: [REDIS / POSTGRES] - Plans and limits: [E.G. free: 1k/mo, pro: 100k/mo] - Counting unit: [REQUESTS / CREDITS PER ENDPOINT] - Reset cadence: [CALENDAR MONTH / ROLLING 30d] </inputs> <task> Build middleware that resolves the caller's plan, atomically increments their usage counter for the current period, compares against the plan limit, sets X-Quota-Limit / X-Quota-Used / X-Quota-Reset headers, and returns 429 with an upgrade hint when exceeded. Include a GET /usage endpoint so customers can see their current consumption, and a period-key scheme that auto-resets. </task> <constraints> - Atomic increment (avoid lost updates under concurrency); period key encodes the reset boundary so it resets automatically. - Distinguish rate limiting (short-term) from quota (billing-period) clearly in comments. - Valid, runnable code with the usage data model. </constraints> <format> Return the middleware plus the /usage endpoint as a code block, then a table mapping plans to limits and the reset logic. </format>
Generates per-key billing-period quota tracking with usage headers and a self-serve usage endpoint, ready to use.
Pro tip: Keep quota (per billing period) separate from rate limiting (per second); ask Claude to run both so a burst does not blow the month.
Validation & Error Handling
5 promptsZod Request Validation Middleware
21/30You are a TypeScript backend engineer who validates every request at the edge. <context> I need reusable validation middleware that checks body, query, and params against Zod schemas and returns clean 400s, returned as one self-contained, commented code block. </context> <inputs> - Framework: [EXPRESS / FASTIFY / NEXT ROUTE HANDLER] - A sample endpoint to validate: [E.G. POST /users with email, password, age] - Error shape I want: [FIELD -> MESSAGE MAP / RFC 9457] - Coerce query strings to numbers/booleans: [YES / NO] </inputs> <task> Build a validate({ body, query, params }) middleware factory that parses each part with its Zod schema, and on failure returns 400 with a structured list of field errors (path + message). On success, replace req values with the parsed, typed data so handlers get clean types. Show it applied to the sample endpoint with its schema. </task> <constraints> - Return ALL validation errors at once, not just the first; include the field path for each. - Strip unknown keys; coerce where asked; never let unvalidated data reach the handler. - Valid, runnable TypeScript with inferred handler types from the schema. </constraints> <format> Return the middleware plus the sample schema and route as a code block, then show an example 400 response body. </format>
Generates reusable Zod validation middleware that returns all field errors and typed request data, ready to use.
Pro tip: Return every error at once; drip-feeding one error per request forces users into a frustrating fix-resubmit loop.
RFC 9457 Problem+JSON Error Handler
22/30You are a backend engineer standardizing API errors to a spec. <context> I want all errors returned as application/problem+json per RFC 9457, from one centralized handler, returned as a self-contained, commented code block. </context> <inputs> - Stack: [EXPRESS / FASTAPI] - Custom error classes I have (if any): [LIST OR NONE] - Base URL for problem type URIs: [E.G. https://api.example.com/problems] - Include stack traces in dev only: [YES] </inputs> <task> Build an AppError base (with type, title, status, detail, and optional extensions) plus a few subclasses (NotFound, Validation, Unauthorized, Conflict), and a central error-handling middleware that serializes any thrown error to a problem+json body { type, title, status, detail, instance } with the right Content-Type. Map unknown errors to a generic 500 without leaking internals. </task> <constraints> - Content-Type application/problem+json; never leak stack traces or DB errors to clients in production. - Every error has a stable, documentable type URI; validation errors include an errors[] extension member. - Valid, runnable code; a single place converts errors to responses. </constraints> <format> Return the error classes plus the handler as a code block, then show two example problem+json responses (404 and validation 422). </format>
Builds a centralized RFC 9457 problem+json error handler with typed error classes, ready to use.
Pro tip: Give each error a stable type URI; you can later publish docs at those URLs so clients can look up what went wrong.
Pydantic Validation with Custom Validators
23/30You are a Python API engineer who enforces strict, meaningful input rules. <context> I need Pydantic v2 models with custom validators and clean 422 error formatting for a specific payload, returned as one self-contained, commented code block. </context> <inputs> - Payload and rules: [E.G. signup: email valid, password >=12 with mixed case, age 13-120, referralCode optional pattern] - Cross-field rules: [E.G. endDate must be after startDate] - Framework: [FASTAPI / STANDALONE PYDANTIC] - Error format: [DEFAULT / CUSTOM FLAT MAP] </inputs> <task> Build the model(s) with field constraints (types, ranges, patterns), field_validators for single-field rules, and a model_validator for cross-field rules. If FastAPI, add an exception handler that reshapes RequestValidationError into a clean { field: message } map. Include examples of both a passing and a failing payload. </task> <constraints> - Use Pydantic v2 syntax; validators must raise clear, user-facing messages (not internal jargon). - Cross-field checks go in a model_validator(mode="after"); no rules duplicated in the endpoint. - Valid, runnable code with comments on each rule. </constraints> <format> Return the models plus the handler as a code block, then show the exact 422 body for the failing payload. </format>
Generates strict Pydantic v2 models with field and cross-field validators and clean 422 output, ready to use.
Pro tip: Put multi-field rules in a model_validator, not the route; that keeps validation reusable and your handler thin.
Consistent JSON Error Envelope + Codes
24/30You are an API designer defining a single error contract for all clients. <context> I want every error response to share one JSON envelope with a machine-readable code, so front-end and SDK code can handle errors uniformly. Return one self-contained, commented code block plus the code catalog. </context> <inputs> - Stack: [DESCRIBE] - Envelope shape preference: [E.G. { error: { code, message, details, requestId } }] - Known error scenarios: [E.G. AUTH_REQUIRED, FORBIDDEN, NOT_FOUND, VALIDATION_FAILED, RATE_LIMITED, CONFLICT] - Correlation id source: [HEADER / GENERATED] </inputs> <task> Build an error catalog mapping each code to an HTTP status and a default message, a helper that builds the envelope (attaching a requestId for tracing), and a central handler that turns thrown errors into the envelope. Ensure every non-2xx path uses it. Include the requestId in a response header too. </task> <constraints> - One envelope for ALL errors; codes are stable and never reused for different meanings. - Always include a requestId clients can quote in support tickets; messages are safe to show users. - Valid, runnable code with the full code-to-status catalog as the single source of truth. </constraints> <format> Return the catalog plus the handler as a code block, then a table of every error code, its status, and when to use it. </format>
Builds a uniform JSON error envelope with a stable error-code catalog and request tracing, ready to use.
Pro tip: Freeze the code strings early; clients will branch on them, so renaming a code later is a breaking change.
Idempotency-Key Handling for POST
25/30You are a payments-grade backend engineer preventing duplicate writes. <context> I need Idempotency-Key support on unsafe POST endpoints so retried requests do not double-charge or double-create, returned as one self-contained, commented code block. </context> <inputs> - Stack and store: [EXPRESS + REDIS / FASTAPI + POSTGRES] - Endpoint to protect: [E.G. POST /payments, POST /orders] - Key TTL: [E.G. 24h] - Request-fingerprint check: [YES / NO] </inputs> <task> Build middleware that reads the Idempotency-Key header: if unseen, acquire a lock, process the request, and store the response (status + body) keyed by the idempotency key; if seen and completed, replay the stored response without re-executing; if seen but in-flight, return 409 (or wait). Optionally verify the request body matches the original fingerprint and reject reuse of a key with a different payload. </task> <constraints> - Store and replay the exact original response; guard concurrent duplicates with a lock, no check-then-act gap. - Detect a reused key carrying a different body and return 422; expire keys after the TTL. - Valid, runnable code with the idempotency record model and comments on the concurrency path. </constraints> <format> Return the middleware plus the record model as a code block, then walk through what happens on a client retry after a network timeout. </format>
Generates Idempotency-Key middleware that safely replays stored responses on retries, ready to use.
Pro tip: Also fingerprint the body; otherwise a client reusing a key with different data silently gets the wrong cached response.
Most people use 10% of Claude. Tutorials unlock the rest.
AI Academy: 300+ hands-on tutorials on Claude, ChatGPT, Midjourney, and 50+ AI tools. New tutorials added every week.
OpenAPI & API Docs
5 promptsOpenAPI 3.1 Spec from a Description
26/30You are an API architect who writes precise OpenAPI specifications. <context> I need a complete, valid OpenAPI 3.1 spec for my API from a plain-English description, returned as one self-contained YAML document I can paste into Swagger Editor. </context> <inputs> - API purpose and base URL: [DESCRIBE + https://api.example.com/v1] - Resources and operations: [E.G. users (CRUD), sessions (login/logout), reports (read)] - Auth scheme: [BEARER JWT / API KEY / OAUTH2] - Key request/response fields per resource: [DESCRIBE] </inputs> <task> Write the full spec: openapi 3.1.0, info, servers, a securitySchemes entry and a global security requirement, paths for every operation with parameters, requestBody, and responses (including 400/401/404/429 where relevant), and reusable components/schemas with types, formats, required arrays, and examples. Reference schemas with $ref rather than repeating them. </task> <constraints> - Must be valid OpenAPI 3.1 that passes a linter; no dangling $refs; realistic examples on schemas. - Reuse schemas via components; include error response schema; document pagination params if listing. - Return YAML, correctly indented, in one block. </constraints> <format> Return the complete OpenAPI YAML as a code block, then a short note on validating it and generating a client SDK from it. </format>
Generates a complete, valid OpenAPI 3.1 YAML spec with schemas, security, and examples from a description, ready to use.
Pro tip: List every status code you actually return per operation; Claude will document them so your SDK and mocks cover the error paths too.
OpenAPI Spec from Existing Code
27/30You are an engineer who documents existing APIs accurately. <context> I will paste my route/handler code and you will reverse-engineer a faithful OpenAPI 3.1 spec from it, returned as one self-contained YAML document. </context> <inputs> - Framework: [EXPRESS / FASTAPI / FLASK / OTHER] - The route + handler code: [PASTE] - Auth mechanism used: [DESCRIBE] - Base URL: [URL] </inputs> <task> Read the code and produce paths for every route you find, inferring path/query/body parameters, request and response schemas from the validation and the objects returned, status codes actually used, and the security scheme. Flag anything ambiguous in comments rather than inventing it, and add examples derived from the code. </task> <constraints> - Only document what the code actually does; mark inferred-or-uncertain parts explicitly, do not fabricate endpoints or fields. - Valid OpenAPI 3.1 that lints clean; schemas reused via components. - Return YAML in one block. </constraints> <format> Return the OpenAPI YAML as a code block, then list any endpoints or fields you could not fully determine from the code so I can confirm them. </format>
Reverse-engineers a faithful OpenAPI 3.1 spec from pasted handler code, flagging uncertain parts, ready to use.
Pro tip: Paste your validation schemas along with the handlers; Claude uses them to write accurate request bodies instead of guessing.
Postman Collection Generator
28/30You are a developer-experience engineer who ships great API onboarding. <context> I need a ready-to-import Postman collection (v2.1) for my API so teammates can call every endpoint immediately, returned as one self-contained JSON document. </context> <inputs> - API base URL and auth: [URL + BEARER/API KEY] - Endpoints (or paste an OpenAPI spec): [LIST OR SPEC] - Environment variables to use: [E.G. {{baseUrl}}, {{token}}] - Sample data for bodies: [DESCRIBE] </inputs> <task> Generate a Postman v2.1 collection: folders per resource, a request per operation with method, {{baseUrl}}-based URL, headers, and example JSON bodies; collection-level auth using a {{token}} variable; and a small test script on the login request that saves the returned token into an environment variable so later requests are authenticated automatically. Include a companion environment file. </task> <constraints> - Valid Postman Collection Format v2.1 JSON that imports without errors; use variables, never hardcoded secrets. - Include realistic example bodies and at least one test script that chains auth. - Return the collection and the environment as two JSON blocks. </constraints> <format> Return the collection JSON and environment JSON as separate code blocks, then note the import steps and how the token auto-populates. </format>
Generates an importable Postman v2.1 collection with variables and a token-chaining test script, ready to use.
Pro tip: Paste your OpenAPI spec as the input; Claude will fan it out into folders and requests instead of you clicking through Postman.
Markdown API Reference from OpenAPI
29/30You are a technical writer who turns specs into developer-friendly docs. <context> I have an OpenAPI spec and need a clean, human-readable Markdown API reference from it, returned as one self-contained Markdown document. </context> <inputs> - The OpenAPI spec (or endpoint list): [PASTE] - Audience: [EXTERNAL DEVS / INTERNAL TEAM] - Include code samples in: [CURL + JS FETCH + PYTHON] - Tone: [CONCISE REFERENCE / TUTORIAL-ISH] </inputs> <task> Write the reference: an intro (base URL, auth, how to get a key), a conventions section (pagination, errors, rate limits), then one section per endpoint with method + path, a one-line purpose, a parameters table (name, in, type, required, description), request and response body examples, status codes, and copy-paste code samples in each requested language. </task> <constraints> - Accurate to the spec; every parameter and status code documented; realistic example values. - Code samples must actually run against the described API (correct headers, auth, body). - Return valid Markdown with tables and fenced code blocks in one document. </constraints> <format> Return the full Markdown reference in one block, then note which sections to keep in a separate "Getting Started" page. </format>
Produces a complete Markdown API reference with parameter tables and multi-language code samples, ready to use.
Pro tip: Ask for curl plus your clients' actual languages; developers copy the sample in their stack far more than they read prose.
Mock Server & Example Responses from a Spec
30/30You are a backend engineer who unblocks frontend teams before the API is built. <context> I need a runnable mock server that serves realistic example responses for my endpoints so the frontend can build in parallel, returned as one self-contained, commented code block. </context> <inputs> - Endpoints (or paste OpenAPI spec): [LIST OR SPEC] - Stack for the mock: [EXPRESS / FASTAPI / JSON-SERVER STYLE] - Behaviors to simulate: [LATENCY, RANDOM 500s, AUTH REQUIRED, PAGINATION] - Realistic sample data theme: [E.G. USERS, PRODUCTS] </inputs> <task> Build a mock server that implements each route returning schema-accurate example JSON, supports the requested behaviors (configurable latency, an optional random-error rate, a fake auth check that 401s without a token, and working pagination over an in-memory dataset), and reads a flag to toggle chaos on/off. Seed a small realistic dataset so responses feel real. </task> <constraints> - Responses must match the real API's shapes and status codes so the frontend can code against them safely. - Toggleable latency and error injection; clearly marked as a mock (no real persistence). - Valid, runnable code with a one-command start and the seed data included. </constraints> <format> Return the mock server as a code block, then note the start command, how to toggle chaos, and how to swap it for the real API later. </format>
Builds a runnable mock server with schema-accurate responses, latency, and error injection, ready to use.
Pro tip: Turn on random 500s and latency early; a frontend that only ever saw happy-path mocks breaks the day the real API is slow.
Frequently Asked Questions
Prompts are the starting line. Tutorials are the finish.
A growing library of 300+ hands-on tutorials on ChatGPT, Claude, Midjourney, and 50+ AI tools. New tutorials added every week.
7-day free trial. Cancel anytime.