FastAPI Guide
Designing your API
It simply allows you to order your arguments so those without default values can be placed ahead of those that can. It also ensures that keyword arguments are used everywhere (which may or may not be desirable when refactoring code). I usually find it unnecessary except in places where I’m using BackgroundTasks
or a depency injected argument somewhere, for example:
@app.get("/")
def get_username(*, db: Session = Depends(get_db), user_id: int) -> str:
return db.query(User).get(user_id).username
See:
What does a star(*) mean in a method parameter?
Order the parameters as you need, tricks
Working with Pydantic objects
Dockerizing a FastAPI application
Dealing with common errors
It usually means the body of your request doesn’t mesh with what your API method is expected. Make sure that the object your passing in matches what you’ve specified, including using the Body(...[,embed=True])
types correctly
See:
Body - Multiple Parameters
Python: FastApi (Unprocessable Entity) error
Usually means you are missing “await” from async method (fastapi/python)
RETURNING
statements don’t return all the columns I specify
RETURNING
statements work okay with fetch_one
/fetch_all
. If you are using execute
, it won’t work.
Mixed Content: The page at 'https://page.com' was loaded over HTTPS, but requested an insecure
XMLHttpRequest endpoint 'http://page.com?filter=xxxx'.
This request has been blocked; the content must be served over HTTPS.
If you add a trailing slash (/) in your API requests it will fix the problem BUT a much easier solution is to the correct proxy headers for Uvicorn. They should look something like this:
upstream api_server {
server ${API_HOST}:${API_PORT} fail_timeout=0;
}
...
server {
...
location ~ /api/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_pass http://api_server;
}
See the following resources:
Failure to load any static files when deploying with HTTPS
fastapi-react nginx.conf
Add option for adding a trailing slash automatically
Ajax Product Filter does not work in https - Fixed