Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Using the Request Directly

Up to now, you have been declaring the parts of the request that you need with their types.

Taking data from:

  • The path as parameters.
  • Headers.
  • Cookies.
  • etc.

And by doing so,FastAPI is validating that data, converting it and generating documentation for your API automatically.

But there are situations where you might need to access theRequest object directly.

Details about theRequest object

AsFastAPI is actuallyStarlette underneath, with a layer of several tools on top, you can use Starlette'sRequest object directly when you need to.

It would also mean that if you get data from theRequest object directly (for example, read the body) it won't be validated, converted or documented (with OpenAPI, for the automatic API user interface) by FastAPI.

Although any other parameter declared normally (for example, the body with a Pydantic model) would still be validated, converted, annotated, etc.

But there are specific cases where it's useful to get theRequest object.

Use theRequest object directly

Let's imagine you want to get the client's IP address/host inside of yourpath operation function.

For that you need to access the request directly.

fromfastapiimportFastAPI,Requestapp=FastAPI()@app.get("/items/{item_id}")defread_root(item_id:str,request:Request):client_host=request.client.hostreturn{"client_host":client_host,"item_id":item_id}

By declaring apath operation function parameter with the type being theRequestFastAPI will know to pass theRequest in that parameter.

Tip

Note that in this case, we are declaring a path parameter beside the request parameter.

So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI.

The same way, you can declare any other parameter as normally, and additionally, get theRequest too.

Request documentation

You can read more details about theRequest object in the official Starlette documentation site.

Technical Details

You could also usefrom starlette.requests import Request.

FastAPI provides it directly just as a convenience for you, the developer. But it comes directly from Starlette.


[8]ページ先頭

©2009-2026 Movatter.jp