Ruff and mypy on an API Project

Ruff finds likely mistakes in an API's code and lays out every file the same way, and mypy reads the type hints that FastAPI, Pydantic and the data module already have to find values that can't be what a function expects, both set up once for the whole project in pyproject.toml.

Journeyman · Python · FastAPI · Software Development · Updated

By

After this lesson you can

  • Run ruff check, ruff check --fix and ruff format on an API project, and keep Ruff's settings in pyproject.toml
  • Run mypy on an API project, read what it reports about the types FastAPI and Pydantic give it, and fix the code

Key takeaways

  • ruff check finds likely mistakes such as an unused import or == None, and ruff check --fix makes the fixes Ruff is sure of. The rest are yours.
  • ruff format lays out every file the same way, and ruff format --check only asks whether a file would change.
  • A project keeps its tools' settings in pyproject.toml, so everyone, and every computer that checks the code, runs them the same way.
  • mypy reads the hints an API already has (route parameters, Pydantic models, the data module) and reports each value that can't be what a function expects.
  • disallow_untyped_defs = true makes mypy report a function with no hints instead of skipping it, and VS Code's Ruff extension can format each file when you save.

On a team, a change with an unused import or a value of the wrong type gets sent back in code review, and many class projects are graded on tidy code as well as working code. Two tools catch those things before anyone else reads your code: Ruff, for mistakes and layout, and mypy, for types. This lesson sets both up on an API.

The example is the Lost and Found Desk, a campus API for the things students find and hand in, which three students work on together.

Three people, one file

Here's the desk's router for found items, after all three have worked on it. Its tests pass:

import os
import sqlite3
from datetime import date

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel

import items_data
from database import get_db

router = APIRouter(prefix="/items", tags=["items"])


class ItemIn(BaseModel):
    name: str
    found_at: str
    found_on: date


@router.get("/{item_id}")
def read_item(item_id: int, conn: sqlite3.Connection = Depends(get_db, scope="function")) -> dict:
    item = items_data.get_item(conn, item_id)
    if item == None:
        raise HTTPException(status_code=404, detail=f"There's no item {item_id}.")
    return item


@router.post("", status_code=201)
def add_item(new_item: ItemIn, conn: sqlite3.Connection=Depends(get_db, scope="function")) -> dict:
    item_id = items_data.add_item(conn, new_item.name, new_item.found_at, new_item.found_on)
    return {"id": item_id, **new_item.model_dump()}

-> dict is read "returns a dict". A reviewer would send back four things here, and you could hunt for them by eye in every file of every change. Or two tools can find them in a second. Both are pinned in the project's requirements.txt, as ruff==0.17.5 and mypy==2.4.1, so pip install -r requirements.txt in the virtual environment installs them.

Ruff: find the mistakes, then fix them

A linter is a spell checker for code: it reads the code without running it and points at what looks wrong. Ruff is a linter and a formatter in one tool. Its settings go in pyproject.toml, the project's settings file, at the top of the project folder, where every Python tool looks:

[tool.ruff]
line-length = 100

[tool.ruff.lint]
select = ["E", "F", "I"]

[tool.ruff] (read "tool dot ruff") starts Ruff's settings. line-length is the longest a line may be. select picks the rule families: E for the layout rules of PEP 8 (read "pep eight"), Python's style guide; F for likely mistakes; I for imports in a tidy order. Now ruff check . checks every Python file in this folder (the dot):

ruff check .
F401 [*] `os` imported but unused
 --> routers/items.py:1:8
  |
1 | import os
  |        ^^
2 | import sqlite3
3 | from datetime import date
  |
help: Remove unused import: `os`
  |
  - import os
1 | import sqlite3
  |

E711 Comparison to `None` should be `cond is None`
  --> routers/items.py:23:16
   |
21 | def read_item(item_id: int, conn: sqlite3.Connection = Depends(get_db, scope="function")) -> dict:
22 |     item = items_data.get_item(conn, item_id)
23 |     if item == None:
   |                ^^^^
24 |         raise HTTPException(status_code=404, detail=f"There's no item {item_id}.")
25 |     return item
   |
help: Replace with `cond is None`
   |
22 |     item = items_data.get_item(conn, item_id)
   -     if item == None:
23 +     if item is None:
24 |         raise HTTPException(status_code=404, detail=f"There's no item {item_id}.")
   |
note: This is an unsafe fix and may change runtime behavior

Found 2 errors.
[*] 1 fixable with `--fix` (1 unsafe fix available with `--fix --unsafe-fixes`).

Each finding starts with its rule code and what's wrong, then the file, line and column (routers/items.py:23:16), with ^^^^ under the spot. [*] marks a fix Ruff is sure of. Ruff calls the is None fix unsafe, because it can change what the code does, so that one is yours: change line 23 to if item is None:, Python's way of asking whether a value is None. Then --fix makes the safe fix and removes the import:

ruff check --fix .
Found 1 error (1 fixed, 0 remaining).

One layout with ruff format

A code formatter rewrites a file's layout (spaces, quotes, line breaks) without changing what the code does, so nobody argues about spaces again. ruff format . formats every file:

ruff format .
1 file reformatted, 5 files left unchanged

It put spaces around the = in add_item's parameters and wrapped the line to fit 100 characters. ruff format --check . asks the same question without changing anything: it lists each file it would reformat, or says 6 files already formatted. A check that runs on every push, as the next lesson sets up, uses that one.

mypy reads the types your API already has

A type checker reads your code and its type hints without running it, and reports each value that can't be what its hint promises. mypy (read "my-pie") is a type checker for Python, and its settings go in the same file:

[tool.mypy]
disallow_untyped_defs = true

mypy skips a function that has no hints at all, so disallow_untyped_defs = true makes it report that function instead. Then mypy .:

mypy .
items_data.py:10: error: Incompatible return value type (got "int | None", expected "int")  [return-value]
routers/items.py:30: error: Argument 4 to "add_item" has incompatible type "date"; expected "str"  [arg-type]
Found 2 errors in 2 files (checked 6 source files)

An API is full of hints already. ItemIn says found_on is a date, so mypy knows new_item.found_on is one, and the data module's add_item asks for found_on: str, the text SQLite stores. The tests passed only because sqlite3 turned the date into text by itself, with a DeprecationWarning that pytest printed and nobody read. On line 10, add_item promises an int, but the type hints for sqlite3, which come with mypy, say cursor.lastrowid is int | None. Both fixes are small:

    if cursor.lastrowid is None:
        raise RuntimeError("SQLite gave the new item no id.")
    return cursor.lastrowid
    item_id = items_data.add_item(conn, new_item.name, new_item.found_at, new_item.found_on.isoformat())

.isoformat() turns the date into text such as "2026-11-12". Now mypy . says Success: no issues found in 6 source files. The new line is too long for Ruff, so ruff format . once more: run all three until each is quiet.

Ruff in VS Code

Install Ruff by Astral from VS Code's Extensions view. It reads the same pyproject.toml and underlines each finding as you type:

VS Code with the Ruff extension: in routers/items.py, import os on line 1 is faded out as unused, item == None on line 23 is underlined, and the Problems panel lists both findings, F401 and E711, with their line numbers

To format every Python file when you save it, open the Command Palette (Ctrl+Shift+P, or Cmd+Shift+P on a Mac), choose Preferences: Open User Settings (JSON), and add these lines inside the outer braces:

"[python]": {
    "editor.defaultFormatter": "charliermarsh.ruff",
    "editor.formatOnSave": true
}

Mypy Type Checker by Microsoft, from the same view, does the same for mypy's errors.

Check yourself

2 questions to try on the lesson page.

So what

Ruff and mypy read every line of every change the same way, every time, so a reviewer, or a grader, can spend their attention on what your API does.

Key terms

Related