Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 50 ยท Responses, errors and docs

Response classes and OpenAPI docs

Return JSON, plain text, HTML and redirects in FastAPI, then document endpoints with tags, summaries and examples and read the generated openapi.json.

Most FastAPI endpoints return a dictionary or a model and let the framework produce JSON. That is the right default, but APIs also need to send plain text, HTML pages, redirects and files, and to set headers or cookies along the way. FastAPI offers response classes for this.

The second half of the lesson is about documentation. Every FastAPI app publishes a machine-readable description of itself at /openapi.json, and two interactive pages built from it: Swagger UI at /docs and ReDoc at /redoc. You will add tags, summaries and examples, and then read the generated document live, in the same program, with no browser needed.

Pick the response class

JSONResponse The default. Full control of status and headers.
PlainTextResponse Text with no JSON quoting.
HTMLResponse A page for browsers.
RedirectResponse Send the client elsewhere.

Set response_class on the decorator so the docs know the type.

1 / 2

Returning custom responses

If an endpoint returns a Response object directly, FastAPI sends it as is, skipping response-model filtering and conversion. That gives you full control over status, headers and cookies.

Python JSON, text and custom headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A plain str returned from a default endpoint would be sent as a JSON string, with quotes. response_class=PlainTextResponse sends the raw text with text/plain.

When you only need to add a header or cookie to a normal response, there is a lighter way: declare a parameter of type Response, set things on it, and still return your data. FastAPI merges the headers into the final response.

HTML and redirects

HTMLResponse sends markup with text/html. RedirectResponse sends a Location header; the default status is 307, which keeps the HTTP method. Use 303 after a POST to send the browser to a GET page, and 301 or 308 for permanent moves.

Python An HTML page and redirects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The client does not follow redirects unless asked, which is why the first request shows the 308 itself. Never build a redirect target from user input without checking it: an attacker could use your site to bounce visitors to a malicious one.

Other classes cover files (FileResponse), large or generated bodies (StreamingResponse, covered in streaming and WebSockets), and faster JSON (ORJSONResponse, which needs the orjson package).

Making the docs useful

FastAPI already generates docs from your types. A few arguments turn them from adequate into helpful:

  • tags=[...] on an endpoint groups it in the UI.
  • summary is a one-line title; the function's docstring becomes the longer description (Markdown works).
  • response_description and responses={404: {...}} document outcomes besides the success case.
  • deprecated=True marks an endpoint as going away.
  • Field(examples=[...]) and model_config["json_schema_extra"] add example payloads.
  • FastAPI(title=..., description=..., version=...) sets the headline information.
Python A documented endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The docstring became description, the 404 entry joined the automatic 200 and 422 responses, and the deprecated flag is recorded. Everything the docs show is just data in this one JSON document.

Reading /openapi.json

The OpenAPI document has a few top-level keys worth knowing: info (title and version), paths (every URL, then every method), and components.schemas (the Pydantic models your endpoints refer to). Let's explore a real one.

Python Exploring the generated document

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that query parameters are described with their constraints (minimum, maximum), that POST /items lists 201, and that Item lives once under components.schemas and is referenced elsewhere. Client generators and API gateways consume exactly this document.

Swagger UI and ReDoc

In a real server, open /docs for Swagger UI: each endpoint expands, shows its parameters and example body, and has a "Try it out" button that sends a real request. /redoc shows the same information as a three-column reference page that is pleasant to read. Both load their JavaScript from a CDN by default, which is why they can't run in the editor on this page; the /openapi.json you just read is what they are drawn from.

Python
# Turn the pages off or move them (for example in production):
app = FastAPI(docs_url=None, redoc_url="/reference", openapi_url="/api/openapi.json")

Setting openapi_url=None disables the schema and both pages. Whether to publish docs on a public server is a product decision: public APIs usually do, internal ones often hide them or protect them behind authentication.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A route returns a plain str with no response_class. How is it sent?

    The default response class is JSON, so a string becomes a JSON string. Use PlainTextResponse or HTMLResponse for raw text.
  2. 2. After a successful form POST, which redirect status makes the browser fetch the next page with GET?

    303 See Other always switches to GET. 307 and 308 keep the original method.
  3. 3. Where does the longer description of an endpoint in the docs come from by default?

    FastAPI uses the docstring as Markdown description, while summary gives a one-line title.
  4. 4. Which URL serves the machine-readable API description?

    Both /docs (Swagger UI) and /redoc are built from /openapi.json.

Summary

  • Return a Response subclass (JSONResponse, PlainTextResponse, HTMLResponse, RedirectResponse) for full control; set response_class on the decorator so the docs show the right type.
  • Redirects default to 307; use 303 after a POST and 301 or 308 for permanent moves.
  • tags, summary, docstrings, responses, deprecated and Field(examples=...) improve the docs.
  • /openapi.json holds info, paths and components.schemas; Swagger UI (/docs) and ReDoc (/redoc) are views of it.
  • Use docs_url, redoc_url and openapi_url to move or disable them.

Next: share logic between endpoints with dependencies.