Request object#
FastAPI provides the fastapi.Request
object, which represents an incoming request to the application. This page focuses on the properties of this object that can be useful for your applications.
Find out more in:
Using the request directly from the FastAPI official documentation.
Requests page from Starlette documetation.
import pickle
import uvicorn
import requests
import multiprocessing
from pathlib import Path
from fastapi import FastAPI, Request
Getting object#
Here is a trick by which we can research real fastAPI object generated for some endpoint.
The following cell defines an application that uses path parameters, query parameters, and the Request
object. It accepts a Request
, serializes some of it fields so you can try them.
app = FastAPI()
@app.get("/{a}/{b}")
def index(a: int, b: str, c: float, request: Request):
# fastapi.Request can't be saved with pickle, so we save only fields we are
# iterested in with dictionary
save_dict = {
"url": request.url,
"query_params": request.query_params
}
with open("request.pkl", "wb") as f:
pickle.dump(save_dict, f)
return "OK"
The following code runs the newly created API and sends a request to the corresponding endpoint, resulting in the serialization of the Request
fields. Afterward, the serialized object is unpickled for further processing within the notebook.
proc = multiprocessing.Process(
target=uvicorn.run,
args=(app,),
kwargs={"log_level": "critical"},
daemon=True
)
proc.start()
requests.get("http://localhost:8000/10/hello?c=10.0").content
request_path = Path("request.pkl")
with open(request_path, "rb") as f:
requst_fields = pickle.load(f)
request_path.unlink()
proc.terminate()
Here are the request fields that we saved from the application.
requst_fields
{'url': URL('http://localhost:8000/10/hello?c=10.0'),
'query_params': QueryParams('c=10.0')}