Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
  • 14:51
    JinKazuya commented #771
  • 14:38
    levchik commented #1204
  • 14:21
    vincentsarago commented #596
  • 10:45
    mariacamilagl synchronize #1220
  • 10:25
    nsidnev commented #1219
  • 08:29
    samuelcolvin commented #1226
  • 08:14
    nsidnev commented #1219
  • 06:03
    tiangolo commented #1221
  • 06:02
    nskalis commented #963
  • 05:55
    github-actions[bot] commented on d4f3ca1
  • 05:54
    tiangolo commented #841
  • 05:54

    tiangolo on 0.54.1


  • 05:53
    github-actions[bot] commented on d4f3ca1
  • 05:51

    tiangolo on master

    :memo: Update release notes :bookmark: Release 0.54.1 (compare)

  • 05:43
    github-actions[bot] commented on a46bbc5
  • 05:42

    tiangolo on handle-setup-dbs


  • 05:41

    tiangolo on master

    :white_check_mark: Update datab… (compare)

  • 05:41
    tiangolo closed #1226
  • 05:39
    codecov[bot] commented #1226
  • 05:39
    codecov[bot] commented #1226

When running locally, my main.py containers:

if __name__ == "__main__":
    uvicorn.run(app, host="", port=8000, log_level="info")

And in Docker I tried both the prebuilt images with the COPY command and the right ENV variables or the base Python image and then running the command myself but they both run into this issue

I'm not entirely sure how to debug this issue or what could cause it
David Asaf

@zero-shubham Thanks for the response. I ended up falling into what your screenshots showed a bit after I posted that. I'm still trying to accomplish this type of workflow compared to Marshmallow: marshmallow-code/flask-marshmallow#136

I know the 2 libraries aren't meant to be interchangeable, but it would be awesome if I could achieve the above in Pydantic

Hey guys,
I have models seperated for each module, but when I try to do some api operation which includeUser I get this error:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class User->user, expression 'Item' failed to locate a name ("name 'Item' is not defined"). If this is a class name, consider adding this relationship() to the <class 'orex.user.m
odels.User'> class after both dependent classes have been defined.

I am sure that I have updated this with relationship notation:

class User(Base):
 id = Column(GUID, primary_key=True, default=uuid.uuid4)

item = relationship("Item", back_populates="user")


class Item(Base):
 id = Column(GUID, primary_key=True, default=uuid.uuid4)

user = relationship("User",back_populates="item")
What's your opinion or fix on this?
Nikhil M Jain
How to specify that a query param can only have values defined in a Enum? And any other value should result in a validation error.
Maurício Eduardo Loschi Batista
@NikhilMJain I believe that this is what you're looking for: https://fastapi.tiangolo.com/tutorial/path-params/#working-with-python-enumerations

By the way, for the issue that I have posted above, If I go to User and write

from item import Item

Then it would work, but that's not the way this should work :(

Nikhil M Jain
@eddloschi Thank you.
Akshay Verma
Hi All, I am excited by FastAPI and want to use it for our next project where the service acts as a sort of microservice fetching data and processing it and saving the output to another service. There will definitely be Pandas and Dataframe related processing which would be called by an API. How can I run this type of processing to gain most advantage out of the async capabilities of the framework? Typically the process would be running self-contained as in no mutliprocessing or distributed computing just within a single process inside a docker container. What would be the best strategy to handle such loads with FastAPI?
Andreas Jung
Is there some way in FastAPI to implemented Flask's https://pythonise.com/series/learning-flask/python-before-after-request functionality? Usecase is to check some application specific headers for each request and for injecting some headers to the response.
Tihomir Totev
Hi, @zopyx! I think you can use the custom http middleware (https://fastapi.tiangolo.com/tutorial/middleware/).
vauxia When creating a router.post function, for /parent/{parent_id}/child, is there a way to somehow access or include the parent_id in the contents of data_in: Child?
vauxia So like, if the Child class has a required parent_id field, is there a way to get at it from the path before validation kicks in?
David Asaf
@zopyx checkout FastAPI middleware https://fastapi.tiangolo.com/tutorial/middleware/
Sharath MK

Hi Team. I wanted to use one POST endpoint to accept json or file as request body based on content-type. I have below code,

 @router.post("/{project_id}/models/{model_id}/predict", responses={200: {"content": {"application/pdf": {}}}})
    def post(self, project_id: ProjectId, model_id: ModelId, predict_data: PredictInputData,
             files: List[UploadFile] = File(...)) -> PredictResponse:

But i get only one value in Request Body drop down.
Requesting to please help @tiangolo

Tosin Mash
How can I achieve this, please?
class beautifulwrapper:

    def __init__(self, colour):
        self.colour = colour

    def __call__(self, f):

        def route_func(*args, **kwargs):
            print(f'\nWrapping route colourfully...')

            f(*args, **kwargs)

        return route_fun

def route_func(request: Request):

    return {'message': 'Works!'}
I'd like to decorate my route function but when I make requests I encounter this:
    "detail": [
            "loc": [
            "msg": "field required",
            "type": "value_error.missing"
            "loc": [
            "msg": "field required",
            "type": "value_error.missing"
@takwas , I'm just starting with FastAPI, I can 't figure out right now what might be your problem. However looking at your code, your are decorating your route with the class it self, without initialized it first. Also, look's like the pattern with FastAPI should be using the class Depends, right?
Maybe you can adapt as explained here:
Anthony Lukach
Question about Pydantic + OpenAPI: I have some pydantic classes in a my_model file called Create and Output. In OpenAPI output, they are only labelled as Create or Output. Is there a way to override that name when defining the class (without actually renaming the class) so I can get something like MyModelCreate?
David De Sousa
hey guys, not precisely fastapi related, more an asyncio stuff
but I'm creating a task with loop.create_task inside the startup event, I want that if that task raises an exception, the server shuts down, can't seem to find a way yet.
any ideas?
@alukach I didn't understand you well, do you want to rename the name that appears on the OpenAPI docs? If is that, you can do it using summary as explained here:
If you only want to rename the class it self, without change it's name, you can create a new variable pointing to the class, in you case:
MyModelCreate = Create
And now you use the MyModelCreate directly instead of the Create class.
Not the right place to ask guys, but is there any way to validate IBAN, inside a pydantic model?
@dedsm you can kill the process (if exception is raised at any time). If you need exception on startup then it is simpler.
David De Sousa
yeah I ended up doing that, adding a done_callback to the app, it feels wrong
Anthony Lukach

@fullonic_gitlab to clarify, I enjoy using a pattern like schemas.item.Create as it makes it easy to import just the schemas module into my endpoints.py file and then reference the appropriate schemas. However, when doing this, the schemas are represented in my OpenAPI docs as Create, which doesn't describe their purpose very well. I'd love to be able to keep the same class name and import paths, but have them rendered as ItemCreate (or something similar) in the OpenAPI docs. I was hoping there would be a way to direct the OpenAPI docs to label my schema class differently than its class name.

So, to address your question: renaming the class isn't what I had hoped for because it would mean I would have to restructure how I reference those schemas in my api handlers.

Markku Laine

I have the following models and endpoint, whose output is shown below:

# Models
class UserCreate(BaseModel):
    name: str

class User(UserCreate):
    id: str

# Endpoint
@events_router.post("/demo", response_model=User)
async def create_user(user_in: UserCreate):
    user = User(**user_in.dict(), id=str(uuid.uuid4()))
    return user

# Output
    "name": "John Doe",
    "id": "0f3468e8-22d1-472a-ba11-92e8ed8d2b76"

How can I change the order of output fields so that id comes before name? According to https://pydantic-docs.helpmanual.io/usage/models/#field-ordering , Pydantic preserves the order of fields, but how to control that when dealing with inherited models?

Maurício Eduardo Loschi Batista
Anybody tested fastapi + sqlalchemy under high load? When I benchmarked my code using wrk, several exceptions were thrown. I suspect it could be concurrency problems caused by sqlalchemy, but could also be something wrong with my code
@dedsm difficult to give a hint without knowing exact issue. Note: please use @ to address message explicitly.
David De Sousa
@madkote it is solved, but it doesn't feel right, but that's precisely one of the main selling points of trio
Ralph Soika

When I try to install fastapi via pip from my requirements.txt file I see the following error:

$ pip install -r requirements.txt
Collecting spacy<3.0.0,>=2.2.0 (from -r requirements.txt (line 1))
Collecting fastapi<1.0.0,>=0.53.0 (from -r requirements.txt (line 2))
  Could not find a version that satisfies the requirement fastapi<1.0.0,>=0.53.0 (from -r requirements.txt (line 2)) (from versions: )
No matching distribution found for fastapi<1.0.0,>=0.53.0 (from -r requirements.txt (line 2))

What does this mean? Is my pip version (9.0.1) outdated?

@rsoika Try running:
pip3 install --upgrade pip
pip3 install fastapi==0.54.0
Sebastián Ramírez
New release! :tada: :rocket:
(by FastAPI bot)


@alukach Hi, it's possible to have a self contained code example? So would be easier to reproduce your problem and see if I can help you.
Leif Linse
Am I blind or where is the API docs of FastAPI? I for example want to know which arguments that "Depends" have and want a dry API docs for FastAPI and not the guide docs.
As of now I need to dig the source in github (or clone fastapi and grep trough the sources). But maybe that is how it is.
Hello guys, is there a way to populate database with sqlalchemy, while making migration..
For ex: I have a table that must be populated through a CSVFile, and my goal is when I run the migrations ex :alembic upgrade head, to make the migrations, and also to popullate with data one of my tables, that I specified, or I wrote some logic to get populated from a csv?
Patrick Düggelin
@Patdue Simple solution below if anyone comes across a similar problem.
import asyncio
import threading
import time

from fastapi import FastAPI, HTTPException

app = FastAPI()

sync_lock = threading.Lock()
async_lock = asyncio.Lock()

def wait(seconds: int = 1):
    if sync_lock.locked():
        raise HTTPException(503)

    with sync_lock:

async def async_wait(seconds: int = 1):
    if async_lock.locked():
        raise HTTPException(503)

    async with async_lock:
        await asyncio.sleep(seconds)
Salent Olivick
How to add fastapi-tags to my own projects?
What kind of tags?
is there a workaround for the openAPI docs to show the proper field name of a schema and not the alias?
for response schemas
Awanish Kumar
Is there any documentation available for fastapi with mysql database all operation like Select, Insert, Update and Delete. I have gone through lots of web surfing but did not find the Update part. Does any one know, please share link.
Hi, any detailed guides on implementing OAuth2 in an API that I built. I went through the tutorial but something more robust. Junior dev here so I'm quite stupid lol