YouTip LogoYouTip

Fastapi Request Response

FastAPI Request and Response | Tutorial\n \n\n

FastAPI Request and Response | Tutorial

\n Image 1\n

Understanding Requests and Responses in FastAPI

\n

In FastAPI, requests and responses are at the core of interacting with clients.

\n

FastAPI provides powerful tools to parse request data and generate standardized responses as needed.

\n

HTTP Related Content

\n

For more information on HTTP methods, refer to: HTTP Request Methods.

\n

Request Data

\n

Query Parameters

\n

The following example defines an /items/ route that accepts two query parameters, skip and limit, both of which are integers with default values of 0 and 10 respectively.

\n

Example

\n
\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get("/items/")\ndef read_item(skip:int=0, limit:int=10):\n    return {"skip": skip, "limit": limit}\n    
\n

To start the application, run the following command in the terminal:

\n

uvicorn main:app --reload

\n

Now, open your browser and visit http://127.0.0.1:8000/items/, it will return the default JSON data:

\n Image 2\n

Passing GET request parameters http://127.0.0.1:8000/items/?skip=1&limit=5, it returns the JSON data as shown below:

\n Image 3\n

Path Parameters

\n

We can set parameters in the path for a cleaner URL.

\n

The following example defines a route with a path parameter item_id and a query parameter q.

\n

Example

\n
\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get("/items/{item_id}")\ndef read_item(item_id: int, q: str=None):\n    return {"item_id": item_id, "q": q}\n    
\n

Passing GET request parameters , it returns the JSON data as shown below:

\n Image 4\n

Request Body

\n

Next, we create a /items/ route using the @app.post decorator to indicate that it handles POST requests.

\n

Example

\n
\nfrom pydantic import BaseModel\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\nclass Item(BaseModel):\n    name: str\n    description: str=None\n    price: float\n    tax: float=None\n\n@app.post("/items/")\ndef create_item(item: Item):\n    return item\n    
\n

We define a request body using the Pydantic model Item, which includes multiple fields, some with default values. More about Pydantic can be found here: FastAPI Pydantic Models.

\n

Next, you can open http://127.0.0.1:8000/docs to perform a POST test:

\n

Fill in the request parameters:

\n Image 5\n

The returned result is as follows:

\n Image 6\n

Response Data

\n

Return JSON Data

\n

The route handler function returns a dictionary, which FastAPI automatically converts to JSON format and sends back to the client as a response:

\n

Example

\n
\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get("/items/")\ndef read_item(skip: int=0, limit: int=10):\n    return {"skip": skip, "limit": limit}\n    
\n

The above code, when accessed in the browser at http://127.0.0.1:8000/items/, returns JSON data:

\n Image 7\n

Return Pydantic Model

\n

The route handler function returns an instance of a Pydantic model, which FastAPI automatically converts to JSON format and sends back to the client as a response:

\n

Example

\n
\nfrom pydantic import BaseModel\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\nclass Item(BaseModel):\n    name: str\n    description: str=None\n    price: float\n    tax: float=None\n\n@app.post("/items/")\ndef create_item(item: Item):\n    return item\n    
\n

POST request, the returned data format is as follows:

\n
{ "name": "", "description": " POST Test", "price": 12, "tax": 1}
\n

Request Headers and Cookies

\n

Use Header and Cookie type annotations to get request header and cookie data.

\n

Example

\n
\nfrom fastapi import Header, Cookie\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get("/items/")\ndef read_item(user_agent: str= Header(None), session_token: str=Cookie(None)):\n    return {"User-Agent": user_agent, "Session-Token": session_token}\n    
\n

The above code, when accessed in the browser at http://127.0.0.1:8000/items/, returns JSON data:

\n Image 8\n

Redirection and Status Codes

\n

Use RedirectResponse to implement redirection, redirecting the client to the /items/ route.

\n

Example

\n
\nfrom fastapi import Header, Cookie\nfrom fastapi import FastAPI\nfrom fastapi.responses import RedirectResponse\n\napp = FastAPI()\n\n@app.get("/items/")\ndef read_item(user_agent: str= Header(None), session_token: str=Cookie(None)):\n    return {"User-Agent": user_agent, "Session-Token": session_token}\n\n@app.get("/redirect")\ndef redirect():\n    return RedirectResponse(url="/items/")\n    
\n

The above code, when accessed in the browser at http://127.0.0.1:8000/redirect/, will automatically redirect to http://127.0.0.1:8000/items/ page:

\n Image 9\n

Use HTTPException to throw exceptions, returning custom status codes and detailed information.

\n

Example

\n

The following example returns a 404 status code when item_id is 42:

\n

Example

\n
\nfrom fastapi import HTTPException\n\napp = FastAPI()\n\n@app.get("/items/{item_id}")\ndef read_item(item_id: int):\n    if item_id == 42:\n        raise HTTPException(status_code=404, detail="Item not found")\n    return {"item_id": item_id}\n    
\n

The above code, when accessed in the browser at http://127.0.0.1:8000/items/42/ page displays as follows:

\n Image 10\n

Custom Response Headers

\n

Use JSONResponse to customize response headers:

\n

Example

\n
\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get("/items/{item_id}")\ndef read_item(item_id: int):\n    content = {"item_id": item_id}\n    headers = {"X-Custom-Header": "custom-header-value"}\n    return JSONResponse(content=content, headers=headers)\n    
\n

The above code, when accessed in the browser at http://127.0.0.1:8000/items/42/ page displays as follows, showing our custom response header:

\n Image 11
← Fastapi Path Operation DependeFastapi Api Doc β†’