response-handling-status-codes
📂 Phase: Phase 1 - Rapid Foundation Building (Basics) 🔗 Related Chapters: path-query-parameters · request-body-handling
When building a Web API, the request is only half the story, the response is what is actually delivered to the client. FastAPI provides very flexible response control capabilities, from the simplest data return, to status codes, response headers, exception-handling, and even completely customized response types, you can easily master it. This article connects all the key knowledge points together, allowing you to learn "response processing" in one step.
1. Response Model (Response Model)
Basic implementation and field filtering
Many times, we receive more request data than we ultimately return. For example, the user registration interface receivespassword, but the password must not be passed back to the front end in the response. FastAPI useresponse_modelParameters to declare the "return contract" and automatically filter out fields that should not appear.
In the above code, althoughreturncontainspassword, but becauseresponse_model=PublicUser, FastAPI will usePublicUserThe model "cleans" the output data, leaving onlyid、nameandemail. To the front end, the password is never exposed.
Core value of the model
Don’t think that the response model is as simple as a “filter field”. It can also bring three major benefits:
- Data conversion and verification: returned by the database
DecimalFields can be automatically converted to JSON friendlyfloat; Missing optional fields will be filled with default values; if the field type is incorrect, an error will be reported directly to prevent dirty data from flowing out. - Automatically generate Swagger / OpenAPI documents: Front-end developers can understand field types, required fields, and example values by looking at the document, and communication costs plummet.
- Development Contract: The front-end and back-end share the Pydantic model. Once the interface fields change, both parties must update the model synchronously, which is more secure.
Flexible field control
In addition to using an independent response model, FastAPI also provides three parameters that allow you to flexibly adjust the output fields in a single interface:
response_model_exclude:Exclude certain fieldsresponse_model_include: Contains only specified fields (highest priority)response_model_exclude_unset: Exclude fields that are not explicitly assigned a value
whenresponse_model_exclude_unset=True, even if the model definesemailfield, but as long as it is not explicitly assigned a value in the returned dictionary, it will not appear in the response. In this way, data packetization after "partial update" can be flexibly realized.
2. Status Code (Status Code)
Unified style setting method
Using status codes to tell the client what happened is basic RESTful etiquette. FastAPI has two ways of writing:
- Write numbers directly (small but difficult to maintain)
- Use
fastapi.statusConstant (with IDE automatic completion, clear semantics, highly recommended)
return204It means that the deletion is successful, but the response body has no content and the browser will not jump to the page.
High Frequency Status Code Cheat Sheet
Remember the following status codes, which are basically enough for daily development:
💡 Tip: If you encounter a client parameter transfer error, you can return
400; If the data verification fails, it will be handed over to FastAPI and automatically returned.422; Used for permission issues403, to prevent attackers from guessing whether resources exist404cover.
3. Directly operate the Response object
when simpleresponse_modelandstatus_codeWhen the needs cannot be met (such as dynamically modifying response headers and setting cookies), you can use it directlyResponseor its subclasses.
Fully custom JSON response
JSONResponseIt is a powerful tool for customizing JSON responses. It allows you to temporarily change the status code and add business error headers:
Although I returned hereJSONResponse, but FastAPI will no longer be used at allresponse_modelGo to secondary processing, so you can freely control all the details of the response.
Configure response headers and cookies
In addition to returning directlyJSONResponse, you can also putResponseThe object is injected as a parameter, so that while returning the Pydantic model normally, additional header information is added to the response:
Something to note: once you returnResponseObject, FastAPI will not perform any serialization or model verification on the data. If you want to return the model normally and add a response header, remember to use "InjectionResponseparameter + directreturndictionary or model" method.
4. Switch different response types
By default FastAPI returns JSON, but you can definitely passresponse_classParameters return HTML, plain text, files, and even streaming data.
⚠️ Note: If the return type is not
dictor Pydantic model, and you forgot to specifyresponse_class, FastAPI will try to serialize it to JSON, which may cause errors. Use rightresponse_classThis type of problems can be avoided.
5. Standard exception-handling
Built-in HTTP exception throwing
The most commonly used exception-handling isHTTPException, which terminates the current request anywhere and returns a clear error:
detailIt can be a string or a dictionary/list to facilitate the definition of business error codes and additional information.
Business-level custom exceptions
Business logic errors such as "Insufficient Inventory", useHTTPExceptionAlthough it is also possible, define a dedicated exception class and then pass@app.exception_handler()Registering a handler function will make the code more expressive:
Global exception interception
The production environment is most afraid of exposing internal exceptions (database connection failure, third-party API timeout) directly to the front end. We can intercept Pydantic verification exceptions and unknown ones respectivelyException, unified format output:
🔒 Security Tip: Do not return in global interception
excspecific content (such as stack information) to avoid leaking sensitive details.
6. Multiple status codes and custom response models
An interface may return multiple status codes, and the response body structure corresponding to each status code is also different (for example, 200 returnsdata,404 returnerrorinformation). It can be used at this timeresponsesParameters to describe exactly these branches in the Swagger document.
In this way, in the automatically generated document, the front end can see the response examples of each status code, and feel more confident when calling the API.
7. Universal paging response solution
List interfaces almost always require paging. FastAPI + Pydantic's generic support allows us to write a "define once, use everywhere" universal paging model.
GenericsPaginatedResponse[Item]Tell FastAPI that the data for each page isItemA list of types, corresponding examples will be generated correctly in the document, and type checking will be more stringent.
🧠 Best Practice: Always Give
page_sizeSet an upper limit (such as 100) to prevent malicious or unexpected large requests from causing a sudden increase in database pressure.
8. Summary
We start from the most basic response model and go all the way to exception-handling and paging, basically covering all the response knowledge required to build a professional API. Finally, here’s a cheat sheet to help you quickly review:
After mastering these skills, your FastAPI application can output a standardized, safe, and easy-to-maintain API. In the next step, you can continue to learn dependency injection and middleware to take the architecture further 🚀.

