APIs · Intermediate · 27 min
Return consistent API errors with Problem Details (RFC 9457)
By Padding · Updated 18 Nov 2026
Node.js 26.13 (node:26 image) · Express 5.3.0 · supertest 7.3.2 · Redocly CLI 2.81.0 · FastAPI 0.165.0 (shown, not run)
You will give every error from an Express 5 API the same application/problem+json shape, with a stable type URI per error kind, field errors, no stack traces, a client that handles them all in one place, an OpenAPI description and the same contract in FastAPI.
On this page
Most APIs grow their error bodies one route at a time. One handler returns {"error": "Not found"}, another {"message": "invalid", "code": 12}, and the framework's own 404 page is HTML. Every client then needs a special case per route, and a client written for one error quietly breaks on the next.
RFC 9457, Problem Details for HTTP APIs, fixes the shape. It replaced RFC 7807 in 2023 and defines a JSON object sent with the media type application/problem+json:
type: a URI that names the kind of problem. Clients branch on this and nothing else.title: a short summary that stays the same for every occurrence of that type.status: the HTTP status code, repeated for convenience. It must match the real one.detail: an explanation of this particular occurrence, for a human.instance: a URI that identifies this occurrence.
Any other member is an extension, and clients must ignore extensions they do not know. That last rule is what lets you add fields later without breaking anyone.
You will build a small parcel pickup API in Express 5 where every error, including bad JSON, unknown routes and your own bugs, comes back in this shape. Then you write a client that handles all of them in one function, a test that keeps the format from drifting, an OpenAPI description of each error type, and the same contract in FastAPI.
Step 1 · Create the project
Make a throwaway folder, turn on ES modules, and install Express. The ~ ranges allow patch releases only:
mkdir -p ~/problem-details-demo
cd ~/problem-details-demo
npm init -y
npm pkg set type=module
npm install express@~5.3.0
npm install --save-dev supertest@~7.3.2 @redocly/cli@2.81.0
mkdir -p src testsupertest sends requests to the app in tests, and Redocly CLI checks the OpenAPI file you write at the end.
Check it worked
npm ls --depth=0The list shows express@5.3.0, supertest@7.3.2 and @redocly/cli@2.81.0, or later patch releases of the first two.
Step 2 · Write a catalogue of problem types
Decide your error kinds before writing any handler. Each kind gets a type URI, a fixed title and a status code, all in one module. That module is the contract: a client matches on the URI, so once it is published it never changes, even if you rewrite the title.
Create src/problems.js:
cat > src/problems.js <<'JS'
import { randomUUID } from 'node:crypto'
// Replace example.com with a domain you control. A type URI is permanent once clients use it.
const TYPE_BASE = 'https://example.com/problems/'
export const PROBLEM_TYPES = {
'validation-error': { status: 422, title: 'Request has invalid fields' },
'malformed-json': { status: 400, title: 'Request body is not valid JSON' },
'body-too-large': { status: 413, title: 'Request body is too large' },
'not-found': { status: 404, title: 'Resource not found' },
'slot-full': { status: 409, title: 'Pickup slot is full' },
}
const STANDARD_MEMBERS = new Set(['type', 'title', 'status', 'detail', 'instance'])
export function typeUri(kind) {
return TYPE_BASE + kind
}
export class Problem extends Error {
constructor(kind, { detail, ...extensions } = {}) {
const known = PROBLEM_TYPES[kind]
if (!known) throw new TypeError(`Unknown problem type: ${kind}`)
for (const name of Object.keys(extensions)) {
if (STANDARD_MEMBERS.has(name)) throw new TypeError(`${name} is a standard member, not an extension`)
}
super(detail ?? known.title)
this.name = 'Problem'
this.kind = kind
this.status = known.status
this.detail = detail
this.extensions = extensions
}
}
export function toProblemBody(error) {
const instance = `urn:uuid:${randomUUID()}`
if (!(error instanceof Problem)) {
return { type: 'about:blank', title: 'Internal Server Error', status: 500, instance }
}
const body = { type: typeUri(error.kind), title: PROBLEM_TYPES[error.kind].title, status: error.status }
if (error.detail) body.detail = error.detail
body.instance = instance
return { ...body, ...error.extensions }
}
JSWhat each part does:
- The type URIs are absolute. RFC 9457 lets a type URI point at a page that documents the error, which is a good use for it, but clients should not fetch it automatically. If you have no such page yet, the URI still works as a name.
Problemis the only error your code throws on purpose. It refuses unknown kinds, so a typo fails the first time the line runs instead of sending a type no client has heard of. It also refuses extensions named like standard members, so no handler can overwritetypeorstatusby accident.toProblemBodyturns anything else, meaning a bug, into a bare 500 with the typeabout:blank. The RFC reserves that value for problems that mean no more than their status code, and its title should be the status phrase. No message, no stack trace and no file path from the original error reaches the body.instanceis a freshurn:uuid:for every response. It does not need to be a web address. Support staff can ask a user for it and search the logs, because the next step logs it next to the stack trace.
Check it worked
node --input-type=module -e "import { Problem, toProblemBody } from './src/problems.js'; console.log(toProblemBody(new Problem('not-found', { detail: 'No pickup 7.' }))); console.log(toProblemBody(new Error('secret path /srv/db')))"The first object has type: 'https://example.com/problems/not-found', title, status: 404, detail and an instance starting urn:uuid:. The second is the bare 500, with no trace of secret path.
Step 3 · Send every error through one handler
Express 5 sends errors from async handlers to your error middleware without any try or catch. That makes one function the only place an error becomes a response. Create src/errors.js:
cat > src/errors.js <<'JS'
import { Problem, toProblemBody } from './problems.js'
export function notFound(req, res, next) {
next(new Problem('not-found', { detail: `Nothing is served at ${req.method} ${req.path}.` }))
}
function fromBodyParser(error) {
if (error?.type === 'entity.parse.failed') {
return new Problem('malformed-json', { detail: 'Check the body for a missing quote, comma or bracket.' })
}
if (error?.type === 'entity.too.large') {
return new Problem('body-too-large', { detail: 'Send at most 10 kB.' })
}
return error
}
export function sendProblem(error, req, res, next) {
if (res.headersSent) return next(error)
const body = toProblemBody(fromBodyParser(error))
if (body.status >= 500) {
console.error(JSON.stringify({
msg: 'unhandled error',
instance: body.instance,
method: req.method,
path: req.path,
stack: error?.stack ?? String(error),
}))
}
res.status(body.status).type('application/problem+json').json(body)
}
JSThree things matter here:
notFounddoes not reply. It passes aProblemon, so a request to a route that does not exist gets the same shape as every other error, instead of Express's HTML page.- The JSON parser in front of your routes throws its own errors, marked with a
typeproperty.fromBodyParsermaps the two you will meet to your catalogue; without it, bad JSON from a client would look like your bug and come back as a 500. res.type('application/problem+json')sets the media type beforeres.json, which only addsapplication/jsonwhen no type is set yet. The stack trace goes to the log on standard error, tagged with the sameinstancethe caller sees.
Keep all four parameters on sendProblem, even though next is used only once. Express recognises error middleware by its four arguments.
Check it worked
node --input-type=module -e "import { notFound, sendProblem } from './src/errors.js'; console.log(notFound.length, sendProblem.length)"The output is 3 4: an ordinary middleware and an error middleware.
Step 4 · Add routes that fail in useful ways
The API books parcel pickups into three time slots, each with room for two pickups. Bad input becomes a validation-error with an errors extension listing every field at once, so a client can mark all the wrong fields in one round trip. Each entry has a pointer, a JSON Pointer to the field written as a URI fragment (#/parcels), and a detail. A full slot is a slot-full problem whose extensions say which slot is free next, so the client can offer it without another request.
Create src/app.js:
cat > src/app.js <<'JS'
import express from 'express'
import { notFound, sendProblem } from './errors.js'
import { Problem } from './problems.js'
const SLOT_CAPACITY = new Map([
['09:00', 2],
['11:00', 2],
['14:00', 2],
])
function checkPickup(body) {
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
throw new Problem('validation-error', {
detail: 'Send a JSON object with address, parcels and slot.',
errors: [{ pointer: '#', detail: 'must be a JSON object' }],
})
}
const errors = []
if (typeof body.address !== 'string' || body.address.trim() === '') {
errors.push({ pointer: '#/address', detail: 'must be a non-empty string' })
}
if (!Number.isInteger(body.parcels) || body.parcels < 1 || body.parcels > 20) {
errors.push({ pointer: '#/parcels', detail: 'must be a whole number from 1 to 20' })
}
if (!SLOT_CAPACITY.has(body.slot)) {
errors.push({ pointer: '#/slot', detail: `must be one of ${[...SLOT_CAPACITY.keys()].join(', ')}` })
}
if (errors.length > 0) {
const detail = errors.length === 1 ? '1 field needs fixing.' : `${errors.length} fields need fixing.`
throw new Problem('validation-error', { detail, errors })
}
return { address: body.address.trim(), parcels: body.parcels, slot: body.slot }
}
export function createApp({ pickups = new Map() } = {}) {
const app = express()
app.disable('x-powered-by')
app.use(express.json({ limit: '10kb' }))
const bookedIn = (slot) => [...pickups.values()].filter((p) => p.slot === slot).length
app.post('/pickups', async (req, res) => {
const pickup = checkPickup(req.body)
const booked = bookedIn(pickup.slot)
if (booked >= SLOT_CAPACITY.get(pickup.slot)) {
const nextFreeSlot = [...SLOT_CAPACITY.keys()].find((slot) => bookedIn(slot) < SLOT_CAPACITY.get(slot)) ?? null
throw new Problem('slot-full', {
detail: `The ${pickup.slot} slot already has ${booked} pickups.`,
slot: pickup.slot,
nextFreeSlot,
})
}
const saved = { id: pickups.size + 1, ...pickup }
pickups.set(saved.id, saved)
res.status(201).location(`/pickups/${saved.id}`).json(saved)
})
app.get('/pickups/:id', async (req, res) => {
const pickup = pickups.get(Number(req.params.id))
if (!pickup) throw new Problem('not-found', { detail: `There is no pickup with id ${req.params.id}.` })
res.json(pickup)
})
app.use(notFound)
app.use(sendProblem)
return app
}
JSThen a small entry point that listens. Create src/server.js:
cat > src/server.js <<'JS'
import { createApp } from './app.js'
const port = Number(process.env.PORT ?? 3000)
createApp().listen(port, '127.0.0.1', (error) => {
if (error) throw error
console.log(`Listening on http://127.0.0.1:${port}`)
})
JS
npm pkg set scripts.start="node src/server.js"createApp takes the pickup store as an option, so a test can hand in one that fails on purpose. The 422 for a slot that does not exist and the 409 for a slot that is full are different kinds: the first is the caller's mistake in the request, the second is a fact about the server's state that a correct request can still run into.
Check it worked
node --check src/app.js && node --check src/server.js && echo "syntax ok"The output is syntax ok.
Step 5 · Run the API and read the error responses
Start the server in a second terminal:
cd ~/problem-details-demo
npm startIt prints Listening on http://127.0.0.1:3000. In your first terminal, fill the 09:00 slot and then try it a third time with -i to see the headers:
curl -s -w '\n' --json '{"address": "12 Allen Avenue, Ikeja", "parcels": 2, "slot": "09:00"}' http://127.0.0.1:3000/pickups
curl -s -w '\n' --json '{"address": "4 Moi Avenue, Nairobi", "parcels": 1, "slot": "09:00"}' http://127.0.0.1:3000/pickups
curl -si --json '{"address": "9 Oxford Street, Accra", "parcels": 3, "slot": "09:00"}' http://127.0.0.1:3000/pickupsThe first two replies are the saved pickups with ids 1 and 2. The third is HTTP/1.1 409 Conflict with Content-Type: application/problem+json; charset=utf-8 and this body, with your own UUID:
{"type":"https://example.com/problems/slot-full","title":"Pickup slot is full","status":409,"detail":"The 09:00 slot already has 2 pickups.","instance":"urn:uuid:3f0c...","slot":"09:00","nextFreeSlot":"11:00"}Now send requests that go wrong in other ways, printing the status code after each body:
curl -s -w '\n%{http_code}\n' --json '{"address": " ", "parcels": 0, "slot": "08:00"}' http://127.0.0.1:3000/pickups
curl -s -w '\n%{http_code}\n' --json '{"address": "12 Allen Avenue"' http://127.0.0.1:3000/pickups
curl -s -w '\n%{http_code}\n' http://127.0.0.1:3000/pickups/99
curl -s -w '\n%{http_code}\n' -X DELETE http://127.0.0.1:3000/pickupsEvery reply has the same five members. The first is 422 with "detail":"3 fields need fixing." and an errors list for #/address, #/parcels and #/slot. Then come 400 with the malformed-json type, 404 with There is no pickup with id 99., and 404 with Nothing is served at DELETE /pickups.
Check it worked
Count the distinct shapes. Every error body you saw starts with type, title and status, has a detail and an instance, and comes with Content-Type: application/problem+json. None of them is HTML and none mentions a file or line of your code. A POST with no body at all is a 422 whose single error points at #, the whole document, because Express 5 leaves req.body undefined when there is no JSON to parse.
Step 6 · Handle every error the same way in a client
The payoff is on the client side. One function makes the request, and any problem response becomes the same kind of exception carrying the parsed body. The calling code then switches on type and falls back to title for kinds it does not know yet.
Create client.js in the project folder:
cat > client.js <<'JS'
export class ApiProblem extends Error {
constructor(problem) {
super(problem.detail ?? problem.title)
this.name = 'ApiProblem'
this.problem = problem
}
}
const BASE_URL = process.env.API_URL ?? 'http://127.0.0.1:3000'
export async function callApi(path, { method = 'GET', body } = {}) {
const res = await fetch(new URL(path, BASE_URL), {
method,
headers: body === undefined ? {} : { 'content-type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
})
if (res.ok) return res.json()
const contentType = res.headers.get('content-type') ?? ''
if (contentType.startsWith('application/problem+json')) {
throw new ApiProblem(await res.json())
}
throw new ApiProblem({ type: 'about:blank', title: res.statusText || 'HTTP error', status: res.status })
}
JSThe last line matters more than it looks. A proxy or load balancer in front of your API can still answer with its own HTML error page, so the client wraps that in an about:blank problem too, and the code above it never sees a second error format.
Now a small command that books a pickup and turns problems into messages. Create book.js:
cat > book.js <<'JS'
import { ApiProblem, callApi } from './client.js'
const PROBLEMS = 'https://example.com/problems/'
const MESSAGES = {
[PROBLEMS + 'slot-full']: (p) =>
p.nextFreeSlot ? `That slot is full. The next free slot is ${p.nextFreeSlot}.` : 'Every slot is full today.',
[PROBLEMS + 'validation-error']: (p) =>
p.errors.map((e) => `Check ${e.pointer.replace('#/', '')}: it ${e.detail}.`).join('\n'),
}
const [address, parcels, slot] = process.argv.slice(2)
try {
const pickup = await callApi('/pickups', { method: 'POST', body: { address, parcels: Number(parcels), slot } })
console.log(`Booked pickup ${pickup.id} at ${pickup.slot}.`)
} catch (error) {
if (error instanceof ApiProblem) {
const message = MESSAGES[error.problem.type]
console.log(message ? message(error.problem) : `${error.problem.title} (${error.problem.status})`)
} else {
console.log('Could not reach the pickup service. Check your connection and try again.')
}
}
JSMessages are keyed by type, not by title or detail. Those two are for developers reading responses, and the RFC allows the server to reword them. Keying on the URI also makes translation straightforward: an app used in Lagos, Nairobi and Dakar can hold its own English, Hausa, Swahili or French text for each type and never parse the server's English. The final branch covers the case where no response arrives at all, which is common on mobile data that drops or runs out mid-request.
Try four bookings, the server still running in the other terminal:
node book.js "7 Adeola Odeku Street, Lagos" 1 09:00
node book.js "" 0 08:00
node book.js "7 Adeola Odeku Street, Lagos" 1 11:00
API_URL=http://127.0.0.1:3999 node book.js "7 Adeola Odeku Street, Lagos" 1 11:00Check it worked
The four runs print, in order: That slot is full. The next free slot is 11:00., three Check ... lines (address, parcels and slot), Booked pickup 3 at 11:00., and Could not reach the pickup service. Check your connection and try again. None of the branches knows which route it called.
Stop the server with Ctrl+C. The next step does not need it.
Step 7 · Keep the format from drifting with a test
A format is only consistent while nothing changes it by accident. One helper asserts the parts every problem must have, and each test adds what is specific to its kind. The last test hands the app a store that throws, to prove a real bug still reaches the client as a bare 500.
Create test/problems.test.js:
cat > test/problems.test.js <<'JS'
import assert from 'node:assert/strict'
import { test } from 'node:test'
import request from 'supertest'
import { createApp } from '../src/app.js'
import { typeUri } from '../src/problems.js'
const valid = { address: '5 Independence Avenue, Accra', parcels: 1, slot: '14:00' }
function assertProblem(res, status, type) {
assert.equal(res.status, status)
assert.match(res.headers['content-type'], /^application\/problem\+json/)
assert.equal(res.body.type, type)
assert.equal(res.body.status, status)
assert.equal(typeof res.body.title, 'string')
assert.match(res.body.instance, /^urn:uuid:[0-9a-f-]{36}$/)
}
test('invalid fields are listed with JSON pointers', async () => {
const res = await request(createApp()).post('/pickups').send({ address: '', parcels: 50 })
assertProblem(res, 422, typeUri('validation-error'))
assert.deepEqual(res.body.errors.map((e) => e.pointer), ['#/address', '#/parcels', '#/slot'])
})
test('a body that is not JSON is malformed-json', async () => {
const res = await request(createApp())
.post('/pickups')
.set('Content-Type', 'application/json')
.send('{"address": ')
assertProblem(res, 400, typeUri('malformed-json'))
})
test('unknown pickups and unknown routes are not-found', async () => {
const app = createApp()
assertProblem(await request(app).get('/pickups/7'), 404, typeUri('not-found'))
assertProblem(await request(app).delete('/pickups'), 404, typeUri('not-found'))
})
test('a full slot says which slot is free next', async () => {
const app = createApp()
await request(app).post('/pickups').send(valid).expect(201)
await request(app).post('/pickups').send(valid).expect(201)
const res = await request(app).post('/pickups').send(valid)
assertProblem(res, 409, typeUri('slot-full'))
assert.equal(res.body.nextFreeSlot, '09:00')
})
test('a bug becomes a bare 500 with no internals', async () => {
const broken = {
values() {
throw new Error('disk full at /var/lib/pickups')
},
}
const res = await request(createApp({ pickups: broken })).post('/pickups').send(valid)
assertProblem(res, 500, 'about:blank')
assert.deepEqual(Object.keys(res.body), ['type', 'title', 'status', 'instance'])
assert.doesNotMatch(JSON.stringify(res.body), /disk|\/var\//)
})
JS
npm pkg set scripts.test="node --test"assertProblem is the contract written as code. If someone adds a route that replies with res.status(400).json({ error: '...' }), the next test written for that route fails on the content type.
Check it worked
npm testThe summary at the end reports pass 5 and fail 0. Above it you see one JSON line on standard error with "msg":"unhandled error", the instance and the stack mentioning disk full: the details went to the log, and the test proved they did not go to the client.
Step 8 · Document the error types in OpenAPI
Clients can only handle the types they know exist. An OpenAPI document lists them per operation, so a reader sees that booking can fail with slot-full and what its extensions hold. Define one Problem schema, extend it per type with a fixed type value, and wrap each in a reusable response under the application/problem+json media type.
Create openapi.yaml:
cat > openapi.yaml <<'YAML'
openapi: 3.2.0
info:
title: Parcel pickups API
version: 1.0.0
description: >-
Every error response is a Problem Details object (RFC 9457) sent as
application/problem+json. Branch on `type`; `title` and `detail` are for people.
servers:
- url: http://127.0.0.1:3000
description: Local development
paths:
/pickups:
post:
operationId: bookPickup
summary: Book a parcel pickup
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewPickup'
responses:
'201':
description: The pickup was booked.
content:
application/json:
schema:
$ref: '#/components/schemas/Pickup'
'400':
$ref: '#/components/responses/MalformedJson'
'409':
$ref: '#/components/responses/SlotFull'
'413':
$ref: '#/components/responses/BodyTooLarge'
'422':
$ref: '#/components/responses/ValidationError'
default:
$ref: '#/components/responses/ServerError'
/pickups/{id}:
get:
operationId: getPickup
summary: Get one pickup
parameters:
- name: id
in: path
required: true
schema:
type: integer
minimum: 1
responses:
'200':
description: The pickup.
content:
application/json:
schema:
$ref: '#/components/schemas/Pickup'
'404':
$ref: '#/components/responses/NotFound'
default:
$ref: '#/components/responses/ServerError'
components:
schemas:
NewPickup:
type: object
required: [address, parcels, slot]
properties:
address:
type: string
minLength: 1
parcels:
type: integer
minimum: 1
maximum: 20
slot:
type: string
enum: ['09:00', '11:00', '14:00']
Pickup:
allOf:
- $ref: '#/components/schemas/NewPickup'
- type: object
required: [id]
properties:
id:
type: integer
Problem:
type: object
description: RFC 9457 problem details. Ignore members you do not recognise.
required: [type, title, status, instance]
properties:
type:
type: string
format: uri-reference
title:
type: string
status:
type: integer
minimum: 400
maximum: 599
detail:
type: string
instance:
type: string
format: uri-reference
ValidationProblem:
allOf:
- $ref: '#/components/schemas/Problem'
- type: object
required: [errors]
properties:
type:
const: 'https://example.com/problems/validation-error'
errors:
type: array
items:
type: object
required: [pointer, detail]
properties:
pointer:
type: string
description: JSON Pointer (RFC 6901) to the field, as a URI fragment.
detail:
type: string
SlotFullProblem:
allOf:
- $ref: '#/components/schemas/Problem'
- type: object
required: [slot, nextFreeSlot]
properties:
type:
const: 'https://example.com/problems/slot-full'
slot:
type: string
nextFreeSlot:
type: [string, 'null']
responses:
ValidationError:
description: One or more fields are invalid. Every invalid field is listed in errors.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/ValidationProblem'
example:
type: 'https://example.com/problems/validation-error'
title: Request has invalid fields
status: 422
detail: 1 field needs fixing.
instance: 'urn:uuid:6c1f0d4e-2b7a-4f53-9a8e-0f3d2c1b5a79'
errors:
- pointer: '#/parcels'
detail: must be a whole number from 1 to 20
SlotFull:
description: The slot already has its maximum number of pickups.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/SlotFullProblem'
MalformedJson:
description: The body could not be parsed as JSON.
content:
application/problem+json:
schema:
allOf:
- $ref: '#/components/schemas/Problem'
- type: object
properties:
type:
const: 'https://example.com/problems/malformed-json'
BodyTooLarge:
description: The body is larger than 10 kB.
content:
application/problem+json:
schema:
allOf:
- $ref: '#/components/schemas/Problem'
- type: object
properties:
type:
const: 'https://example.com/problems/body-too-large'
NotFound:
description: No such pickup, or no such route.
content:
application/problem+json:
schema:
allOf:
- $ref: '#/components/schemas/Problem'
- type: object
properties:
type:
const: 'https://example.com/problems/not-found'
ServerError:
description: An unexpected error. No detail is given; quote the instance to support.
content:
application/problem+json:
schema:
allOf:
- $ref: '#/components/schemas/Problem'
- type: object
properties:
type:
const: about:blank
YAML
cat > redocly.yaml <<'YAML'
extends:
- recommended
rules:
# This demo API has no authentication yet. Remove this line when it does.
security-defined: off
YAMLLint it with Redocly's recommended rules:
npx redocly lint openapi.yamlThen check that the document and the code name the same types. This short script fails the day someone adds a kind to src/problems.js without documenting it:
node --input-type=module -e "
import { readFileSync } from 'node:fs'
import { PROBLEM_TYPES, typeUri } from './src/problems.js'
const doc = readFileSync('openapi.yaml', 'utf8')
const missing = Object.keys(PROBLEM_TYPES).filter((kind) => !doc.includes(typeUri(kind)))
console.log(missing.length ? 'Undocumented: ' + missing.join(', ') : 'All problem types documented')
"Check it worked
redocly lint reports no errors and exits normally; read any warnings it prints, as they do not fail the run. The script prints All problem types documented. Add a sixth kind to PROBLEM_TYPES and run it again to see it listed as undocumented, then remove it.
Step 9 · Return the same problems from FastAPI
If part of your system runs on Python, its errors should use the same type URIs, so one client handles both. FastAPI does not produce Problem Details on its own: its validation errors are {"detail": [...]} with application/json. You replace that with exception handlers, one per source of errors. This step uses FastAPI 0.165.0 and a separate folder:
mkdir -p ~/problem-details-fastapi
cd ~/problem-details-fastapi
python3 -m venv .venv
. .venv/bin/activate
pip install "fastapi[standard]==0.165.0"Save this as main.py:
import logging
from http import HTTPStatus
from typing import Literal
from uuid import uuid4
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from starlette.exceptions import HTTPException as StarletteHTTPException
TYPE_BASE = "https://example.com/problems/" # the same URIs as the Express API
PROBLEM_TYPES = {
"validation-error": (422, "Request has invalid fields"),
"malformed-json": (400, "Request body is not valid JSON"),
"not-found": (404, "Resource not found"),
"slot-full": (409, "Pickup slot is full"),
}
SLOTS = ["09:00", "11:00", "14:00"]
CAPACITY = 2
log = logging.getLogger("pickups")
app = FastAPI()
pickups: list[dict] = []
class Problem(Exception):
def __init__(self, kind: str, detail: str | None = None, **extensions):
self.kind, self.detail, self.extensions = kind, detail, extensions
def problem_response(status: int, body: dict, headers: dict | None = None) -> JSONResponse:
return JSONResponse(body, status_code=status, media_type="application/problem+json", headers=headers)
def problem(kind: str, detail: str | None = None, **extensions) -> JSONResponse:
status, title = PROBLEM_TYPES[kind]
body = {"type": TYPE_BASE + kind, "title": title, "status": status}
if detail:
body["detail"] = detail
body["instance"] = f"urn:uuid:{uuid4()}"
return problem_response(status, {**body, **extensions})
def where(loc) -> dict:
source, *rest = loc
if source == "body":
return {"pointer": "#" + "".join(f"/{part}" for part in rest)}
return {"parameter": str(rest[-1]) if rest else source}
@app.exception_handler(Problem)
async def on_problem(request: Request, exc: Problem):
return problem(exc.kind, exc.detail, **exc.extensions)
@app.exception_handler(RequestValidationError)
async def on_invalid(request: Request, exc: RequestValidationError):
issues = exc.errors()
if any(issue["type"] == "json_invalid" for issue in issues):
return problem("malformed-json", "Check the body for a missing quote, comma or bracket.")
errors = [{**where(issue["loc"]), "detail": issue["msg"]} for issue in issues]
detail = "1 field needs fixing." if len(errors) == 1 else f"{len(errors)} fields need fixing."
return problem("validation-error", detail, errors=errors)
@app.exception_handler(StarletteHTTPException)
async def on_http_error(request: Request, exc: StarletteHTTPException):
if exc.status_code == 404:
return problem("not-found", f"Nothing is served at {request.method} {request.url.path}.")
status = HTTPStatus(exc.status_code)
body = {"type": "about:blank", "title": status.phrase, "status": status.value,
"instance": f"urn:uuid:{uuid4()}"}
return problem_response(status.value, body, headers=getattr(exc, "headers", None))
@app.exception_handler(Exception)
async def on_bug(request: Request, exc: Exception):
instance = f"urn:uuid:{uuid4()}"
log.error("unhandled error %s", instance, exc_info=exc)
body = {"type": "about:blank", "title": "Internal Server Error", "status": 500, "instance": instance}
return problem_response(500, body)
class NewPickup(BaseModel):
address: str = Field(min_length=1)
parcels: int = Field(ge=1, le=20)
slot: Literal["09:00", "11:00", "14:00"]
def booked_in(slot: str) -> int:
return sum(1 for p in pickups if p["slot"] == slot)
@app.post("/pickups", status_code=201)
async def book_pickup(new: NewPickup):
booked = booked_in(new.slot)
if booked >= CAPACITY:
next_free = next((s for s in SLOTS if booked_in(s) < CAPACITY), None)
raise Problem("slot-full", f"The {new.slot} slot already has {booked} pickups.",
slot=new.slot, nextFreeSlot=next_free)
pickup = {"id": len(pickups) + 1, **new.model_dump()}
pickups.append(pickup)
return pickup
@app.get("/pickups/{pickup_id}")
async def get_pickup(pickup_id: int):
for pickup in pickups:
if pickup["id"] == pickup_id:
return pickup
raise Problem("not-found", f"There is no pickup with id {pickup_id}.")The handlers map each source of errors to the same catalogue:
Problemis your own error, as in Express.RequestValidationErroris raised by FastAPI when Pydantic rejects the input. Each issue has alocsuch as("body", "parcels");whereturns body locations into the same JSON Pointers the Express API sends, and names path or query parameters in aparametermember instead. A body that is not JSON arrives here too, as an issue of typejson_invalid, and becomesmalformed-json.- The handler is registered for Starlette's
HTTPException, not FastAPI's subclass, so it also catches the 404 for a route that does not exist and the 405 for a wrong method. Codes outside your catalogue becomeabout:blankwith the standard status phrase as the title. - The handler for
Exceptioncatches bugs, logs the stack trace with theinstance, and returns the bare 500.
FastAPI's generated /docs still describe its default 422 body. Keep openapi.yaml from the previous step as the published contract, or declare the problem responses per route with the responses argument.
Start it and send the same bad request as before:
fastapi dev main.pycurl -si --json '{"address": " ", "parcels": 0, "slot": "08:00"}' http://127.0.0.1:8000/pickupsCheck it worked
The reply is 422 with content-type: application/problem+json, "type":"https://example.com/problems/validation-error" and an errors list whose pointers are #/parcels and #/slot. The address " " passes here because Pydantic's min_length counts spaces; add str_strip_whitespace=True to the model's config if you want the Express behaviour. Point book.js at it with API_URL=http://127.0.0.1:8000: it still branches on type, so a full slot gives the same message as with Express. The field messages read differently, because each detail here is Pydantic's own msg wording, not text from your catalogue: book.js prints Check parcels: it Input should be greater than or equal to 1. If clients show these to people, map Pydantic's error types (greater_than_equal, less_than_equal, string_too_short, literal_error) to your own detail strings in on_invalid. Stop the server with Ctrl+C.
When you are done with both projects, remove them:
rm -rf ~/problem-details-demo ~/problem-details-fastapiNext steps
- If your error middleware lives in a larger app, structure an Express 5 app with routers and error handling shows where
sendProblemfits alongside request ids and logging. - Choosing the right status code for each problem type is covered in design REST endpoints, resources, methods and status codes.
- Grow the error responses from this tutorial into a full contract in describe an API with an OpenAPI 3.2 document.
- Start the Python side from scratch with build a REST API with FastAPI.
Part of these paths
Related tutorials
- Structure an Express 5 app with routers, middleware and error handlingYou will build a small projects-and-tasks API in Express 5.3 split into routers and modules, with request ids, JSON logs, Zod validation, one central error handler, configuration from environment variables and route tests with supertest.
- Design REST endpoints: resources, methods and status codesYou will design the endpoints of an event ticketing API on one page, build an Express 5 stub that follows it, and prove every status code in the design with curl.
- Describe an API with an OpenAPI 3.2 documentYou will write an OpenAPI 3.2 contract for a ticketing API by hand across several files, lint it clean with Redocly CLI 2, bundle it into one file and generate TypeScript types that a client uses against a mock server.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials