question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to pass a request object as optional to a function in fastAPI?

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI,Query
from starlette.requests import Request
from typing import Optional,
app = FastAPI()
@app.api_route("/endpoint/v1/{my_id}", methods=["GET", "POST", "DELETE"])
async def myFunction(request: Request, my_id: Optional[str] = None, request_type: Optional[str] = None):
#function body
                                                             ):

Description

In the above code, I could able to handle the routing and could able to access the function - myFunction as

import requests
requests.get('http://localhost:7008/endpoint/v1/'),

Then I tried to call the function directly(without routing) as

myFunction()

But it shows the error like

TypeError: myFunction() missing 1 required positional argument: 'request'

Now I have to doubts 1 - How to call a fastAPI function directly (without routing) 2 - How to put the request object parameter as optional in fastAPI function

Operating System

Linux

Operating System Details

No response

FastAPI Version

fastapi==0.75.0

Python Version

3.6.9

Additional Context

No response

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:10

github_iconTop GitHub Comments

1reaction
accelleoncommented, Apr 13, 2022

@pradeepdev-1995 It seems as though the issue with Optional[Request] is that Request isn’t a viable type for pydantic. Pydantic is pretty baked into FastAPI.

This is the actual exception that is being masked by FastAPI’s

  File "pydantic/main.py", line 204, in pydantic.main.ModelMetaclass.__new__
  File "pydantic/fields.py", line 488, in pydantic.fields.ModelField.infer
  File "pydantic/fields.py", line 419, in pydantic.fields.ModelField.__init__
  File "pydantic/fields.py", line 539, in pydantic.fields.ModelField.prepare
  File "pydantic/fields.py", line 801, in pydantic.fields.ModelField.populate_validators
  File "pydantic/validators.py", line 723, in find_validators
RuntimeError: no validator found for <class 'starlette.requests.Request'>, see `arbitrary_types_allowed` in Config

FastAPI is bypassing that function call for dependencies and default parameters such as the type Request. You’re gonna have to not declare the field as Optional[] and instead just pass it None. If you’re using mypy or type checking in your IDE and want to rid yourself of the error you can use type: ignore:

import starlette
@app.api_route("/endpoint/v1/{my_id}", methods=["GET", "POST", "DELETE"])
async def myFunction(request : starlette.requests.Request = None, my_id: Optional[str] = None, request_type: Optional[str] = None):  # type: ignore
0reactions
pradeepdev-1995commented, Apr 13, 2022

@accelleon Thank you. The above solution solved my issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Request Body - FastAPI
To declare a request body, you use Pydantic models with all their power and ... optional (with a default value of None ),...
Read more >
Define a Request parameter as an optional variable type in ...
You can pass the request object as optional like below import starlette @app.api_route("/endpoint/v1/{my_id}", methods=["GET", "POST", ...
Read more >
FastAPI Python Tutorial - 6: Add users: Request body with ...
Welcome to our FastAPI Python Tutorial series. You'll build a basic API using FastAPI as a practice project.In this Part 6 video, ...
Read more >
How to use FastAPI Query Parameters?
In FastAPI, when we declare a function with parameters that are not present as path parameters, they are interpreted as query parameters.
Read more >
How to Create a RESTful API with Python and FastAPI
Any request made to a REST API consists of four essential parts: ... The user_list function takes two optional parameters: min and max....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found