How to modify response information in FastAPI

overview

In FastAPI, the processing of the request is done inside the path manipulation function. The request object and response object are passed as arguments of the path operation function. You use these objects to retrieve data related to requests, generate responses, and so on.

This section describes how to modify the response information in FastAPI using the following versions.

FastAPI v0.100.0
Python v3.11.4
uvicorn v0.22.0

Also, all the code created this time is GitHub is posted on

How to edit response information

A response object is used to construct the response to the client. Used in FastAPI path manipulation functions to set response headers, status codes, data, etc.

The sample code below is an example for understanding the response object in FastAPI. It takes GET requests and generates and returns different kinds of responses.

response.py

from fastapi import FastAPI, Response
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse

app = FastAPI()

@app.get("/json")
async def json_response():
    # Generate JSON response
    return JSONResponse(content={"message": "This is a JSON response"})

@app.get("/html")
async def html_response():
    # generate HTML response
    return HTMLResponse(content="<h1>This is an HTML response</h1>")

@app.get("/custom-header")
async def custom_header_response():
    # set response headers
    response = Response(content="This response has a custom header")
    response.headers["Custom-Header"] = "Custom-Value"
    return response

@app.get("/status-code")
async def status_code_response():
    # set status code
    response = Response(content="Created", status_code=201)
    return response

@app.get("/redirect")
async def redirect_response():
    # execute redirect
    return RedirectResponse(url="/json")

@app.get("/error")
async def error_response():
    # generate error response
    return JSONResponse(content={"error": "An error occurred"}, status_code=500)

Commentary

  • JSON response endpoint (/json)
@app.get("/json")
async def json_response():
    # Generate JSON response
    return JSONResponse(content={"message": "This is a JSON response"})

This endpoint returns a response in JSON format. Specifically, it returns a JSON object {“message”: “This is a JSON response”} as a response.

  • HTML response endpoint (/html)
@app.get("/html")
async def html_response():
    # generate HTML response
    return HTMLResponse(content="<h1>This is an HTML response</h1>")

This endpoint returns an HTML formatted response. Specifically, it returns the HTML “

This is an HTML response

” as a response.

  • Custom Header Response Endpoint (/custom-header)
@app.get("/custom-header")
async def custom_header_response():
    # set response headers
    response = Response(content="This response has a custom header")
    response.headers["Custom-Header"] = "Custom-Value"
    return response

This endpoint returns a response with custom headers. Specifically, it adds a header named “Custom-Header” to the response with a value of “Custom Value”.

  • Status code response endpoint (/status-code)
@app.get("/status-code")
async def status_code_response():
    # set status code
    response = Response(content="Created", status_code=201)
    return response

This endpoint returns a response with a specific status code of 201 (Created). Status code 201 indicates that the resource was created successfully.

  • Redirect Response Endpoint (/redirect)
@app.get("/redirect")
async def redirect_response():
    # execute redirect
    return RedirectResponse(url="/json")

This endpoint will redirect to the “/json” endpoint when accessed.

  • Error response endpoint (/error)
@app.get("/error")
async def error_response():
    # generate error response
    return JSONResponse(content={"error": "An error occurred"}, status_code=500)

This endpoint returns a response with a status code of 500 (Internal Server Error) and an error message. This error message is returned in a JSON object format of {“error”: “An error occurred”}.

Through these endpoints, you can learn how FastAPI handles different kinds of HTTP responses. You should have started your FastAPI application with the following command:

uvicorn main:app --reload

test

curl -X GET http://localhost:8000/json
curl -X GET http://localhost:8000/html
curl -X GET http://localhost:8000/custom-header
curl -X GET http://localhost:8000/status-code
curl -L -X GET http://localhost:8000/redirect (use the "-L" flag to follow redirects)
curl -X GET http://localhost:8000/error

This code generates different types of responses within the path manipulation functions. It shows features such as JSON responses, HTML responses, custom headers, status codes, and more. Concise and flexible response generation is possible using the convenience features of FastAPI.

summary

By using response objects, you can:

  • You can set or change response headers.
  • You can set the HTTP status code of the response.
  • You can set the body data of the response. It can return data in the form of JSON objects, strings, binary data, etc.

Response objects allow you to perform various operations related to response generation within your FastAPI application. Response objects have many properties and methods that allow for a high degree of customization and control.