Skip to main content

flake8-fastapi

Latest Commit
Package version

A flake8 plugin that helps you avoid simple FastAPI mistakes.

Installation

First, install the package:

pip install flake8-fastapi

Then, check if the plugin is installed using flake8:

$ flake8 --version
3.9.2 (flake8-fastapi: 0.2.0, mccabe: 0.6.1, pycodestyle: 2.7.0, pyflakes: 2.3.1) CPython 3.8.11 on Linux

Rules

CF001 - Route Decorator Error

Developers that were used to flask can be persuaded or want to use the same pattern in FastAPI:

from fastapi import FastAPI

app = FastAPI()


@app.route("/", methods=["GET"])
def home():
    return "Hello world!"

But on FastAPI, we have a simpler way to define this (and is the most known way to create endpoints):

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def home():
    return "Hello world!"

CF002 - Router Prefix Error

On old FastAPI versions, we were able to add a prefix only on the include_router method:

from fastapi import APIRouter, FastAPI

router = APIRouter()


@router.get("/")
def home():
    ...


app = FastAPI()
app.include_router(router, prefix="/prefix")

Now, it's possible to add in the Router initialization:

from fastapi import APIRouter, FastAPI

router = APIRouter(prefix="/prefix")


@router.get("/")
def home():
    ...


app = FastAPI()
app.include_router(router)

CF008 - CORSMiddleware Order

There's a tricky issue about CORSMiddleware that people are usually unaware. Which is that this middleware should be the last one on the middleware stack. You can read more about it here.

Let's see an example of what doesn't work:

from fastapi import FastAPI

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*']
)
app.add_middleware(GZipMiddleware)

As you see, the last middleware added is not CORSMiddleware, so it will not work as expected. On the other hand, if you change the order, it will:

from fastapi import FastAPI

app = FastAPI()

app.add_middleware(GZipMiddleware)
app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*']
)

CF009 - Undocumented HTTPException

Currently, there's no automatic solution to document the HTTPExceptions, besides the experimental package fastapi-responses.

For that reason, it's easy to forget the documentation, and have a lot of undocumented endpoints. Let's see an example:

from fastapi import FastAPI, HTTPException

app = FastAPI()


@app.get("/")
def home():
    raise HTTPException(status_code=400, detail="Bad Request")

The above endpoint doesn't have a responses field, even if it's clear that the response will have a 400 status code.

CF011 - No Content Response

Currently, if you try to send a response with no content (204), FastAPI will send a 204 status with a non-empty body. It will send a body content-length being 4 bytes.

You can verify this statement running the following code:

# main.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/", status_code=204)
def home():
    ...

Now feel free to run with your favorite server implementation:

uvicorn main:app

Then use curl or any other tool to send a request:

$ curl localhost:8000
*   Trying 127.0.0.1:8000...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8000 (#0)
> GET / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.68.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 204 No Content
< date: Sat, 24 Jul 2021 19:21:24 GMT
< server: uvicorn
< content-length: 4
< content-type: application/json
<
* Connection #0 to host localhost left intact

This goes against the RFC, which specifies that a 204 response should have no body.

License

This project is licensed under the terms of the MIT license.

Metadata

Release files for flake8-fastapi 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flake8-fastapi 0.7.0
File Size Uploaded
flake8-fastapi-0.7.0.tar.gz 9.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for flake8-fastapi 0.7.0
File Interpreter ABI Platform
flake8_fastapi-0.7.0-py3-none-any.whl Python 3 none any Details

Total release size: 18.7 kB

Release files / flake8-fastapi-0.7.0.tar.gz

Download URL flake8-fastapi-0.7.0.tar.gz
Size 9.0 kB
Tags Source
SHA-256 checksum
How to use checksums
f234ddc1c2445ded69465362069863c7a2435c641769c9a3f25eab7a02b815c5
BLAKE2b-256 checksum
How to use checksums
0b0eeb1515257fb82fdfde02b506fdcfcfdb3823d279c41207db21d341668b38
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.13 CPython/3.8.12 Linux/5.13.0-1031-azure

Release files / flake8_fastapi-0.7.0-py3-none-any.whl

Download URL flake8_fastapi-0.7.0-py3-none-any.whl
Size 9.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
33f347eff226c7675fdb99086fdf3075c00fcfb51a50c8a8950f594af37f65ec
BLAKE2b-256 checksum
How to use checksums
88062d106d674766c58259580fe381e45f09cc1ffa4c4c978b2eb61f5fb9e7b0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.13 CPython/3.8.12 Linux/5.13.0-1031-azure

Release history Release notifications | RSS feed

This release

0.7.0 This release

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.0

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page