Is it possible to change the output alias in pydantic?

Update (2023-10-07): Check the comments in the question for other answers and this answer in the same question for pydantic 2.0 or newer. Switch aliases and field names and use the allow_population_by_field_name model config option: class TMDB_Category(BaseModel): strCategory: str = Field(alias=”name”) strCategoryDescription: str = Field(alias=”description”) class Config: allow_population_by_field_name = True Let the aliases configure the … Read more

FastAPI: Retrieve URL from view name ( route name )

We have got Router.url_path_for(…) method which is located inside the starlette package Method-1: Using FastAPI instance This method is useful when you are able to access the FastAPI instance in your current context. (Thanks to @Yagizcan Degirmenci) from fastapi import FastAPI app = FastAPI() @app.get(‘/hello/’) def hello_world(): return {“msg”: “Hello World”} @app.get(‘/hello/{number}/’) def hello_world_number(number: int): … Read more

A minimal fastapi example loading index.html

Option 1: Static file mounting It was easier than expected. Just needed to put all static files including index.html into static folder in project directory and mount static files. from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() app.mount(“/static”, StaticFiles(directory=”static”), name=”static”) That’s it. My index.html is now available under http://localhost:8000/static/index.html. In case it … Read more

Keep getting “307 Temporary Redirect” before returning status 200 hosted on FastAPI + uvicorn + Docker app – how to return status 200?

It happens because the exact path defined by you for your view is yourdomainname/hello/, so when you hit it without / at the end, it first attempts to get to that path but as it is not available it checks again after appending / and gives a redirect status code 307 and then when it … Read more

Catch `Exception` globally in FastAPI

In case you want to capture all unhandled exceptions (internal server error), there’s a very simple way of doing it. Documentation from fastapi import FastAPI from starlette.requests import Request from starlette.responses import Response from traceback import print_exception app = FastAPI() async def catch_exceptions_middleware(request: Request, call_next): try: return await call_next(request) except Exception: # you probably want … Read more

Make every field as optional with Pydantic

This method prevents data validation Read this by @Anime Bk: https://stackoverflow.com/a/75011200 Solution with metaclasses I’ve just come up with the following: class AllOptional(pydantic.main.ModelMetaclass): def __new__(cls, name, bases, namespaces, **kwargs): annotations = namespaces.get(‘__annotations__’, {}) for base in bases: annotations.update(base.__annotations__) for field in annotations: if not field.startswith(‘__’): annotations[field] = Optional[annotations[field]] namespaces[‘__annotations__’] = annotations return super().__new__(cls, name, bases, … Read more

How to add both file and JSON body in a FastAPI POST request?

As per FastAPI documentation: You can declare multiple Form parameters in a path operation, but you can’t also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using application/x-www-form-urlencoded instead of application/json (when the form includes files, it is encoded as multipart/form-data). This is not a … Read more

What are the advantages of using Depends in FastAPI over just calling a dependent function/class?

FastAPI will also inject parameters from the request into your dependencies, and include them into the OpenApi specification. This allows you to re-use parameters, which can help you write less code, especially if your project grows large. Without the dependency injection you’d have to specify the parameters on every route, every time. In this example … Read more

How to set up and tear down a database between tests in FastAPI?

For cleaning up after tests even when they fail (and setting up before tests), pytest provides pytest.fixture. In your case you want to create all tables before each test, and drop them again afterwards. This can be achieved with the following fixture: @pytest.fixture() def test_db(): Base.metadata.create_all(bind=engine) yield Base.metadata.drop_all(bind=engine) And then use it in your tests … Read more

Sharing python objects across multiple workers

It is not possible to share a python object between different processes straightforwardly. The facilities included in the multiprocessing module (like managers or shared memory) are not suitable for sharing resources between workers, since they require a master process creating the resources and do not have the durability property. Also server processes can be run … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)