FastAPI Request and Response | Tutorial
\nUnderstanding Requests and Responses in FastAPI
\nIn FastAPI, requests and responses are at the core of interacting with clients.
\nFastAPI provides powerful tools to parse request data and generate standardized responses as needed.
\nHTTP Related Content
\nFor more information on HTTP methods, refer to: HTTP Request Methods.
\nRequest Data
\nQuery Parameters
\nThe 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.
\nExample
\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:
\nuvicorn main:app --reload
\nNow, open your browser and visit http://127.0.0.1:8000/items/, it will return the default JSON data:
\nPassing GET request parameters http://127.0.0.1:8000/items/?skip=1&limit=5, it returns the JSON data as shown below:
\nPath Parameters
\nWe can set parameters in the path for a cleaner URL.
\nThe following example defines a route with a path parameter item_id and a query parameter q.
\nExample
\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:
\nRequest Body
\nNext, we create a /items/ route using the @app.post decorator to indicate that it handles POST requests.
\nExample
\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.
\nNext, you can open http://127.0.0.1:8000/docs to perform a POST test:
\nFill in the request parameters:
\nThe returned result is as follows:
\nResponse Data
\nReturn JSON Data
\nThe route handler function returns a dictionary, which FastAPI automatically converts to JSON format and sends back to the client as a response:
\nExample
\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:
\nReturn Pydantic Model
\nThe 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:
\nExample
\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
\nUse Header and Cookie type annotations to get request header and cookie data.
\nExample
\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:
\nRedirection and Status Codes
\nUse RedirectResponse to implement redirection, redirecting the client to the /items/ route.
\nExample
\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:
\nUse HTTPException to throw exceptions, returning custom status codes and detailed information.
\nExample
\nThe following example returns a 404 status code when item_id is 42:
\nExample
\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:
\nCustom Response Headers
\nUse JSONResponse to customize response headers:
\nExample
\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
YouTip