Skip to content

FastAPI CRUD API

CRUD stands for Create, Read, Update and Delete.

Those are the basic operations you would perfom on a database entity. In this blog post, let’s take a super-simple User entity with name and age properties.


FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.

The key features are:

  • Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic).
  • Fast to code: Increase the speed to develop features.
  • Fewer bugs: Reduce about 40% of human (developer) induced errors.
  • Intuitive: Great editor support. Completion everywhere. Less time debugging.
  • Easy: Designed to be easy to use and learn. Less time reading docs.
  • Short: Minimize code duplication. Multiple features from each parameter declaration.
  • Robust: Get production-ready code. With automatic interactive documentation.
  • Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.

First installation of FastAPI:

Terminal window
# move into the correct directory
cd user-crud
# create the virtual environment and activate it
python3 -m venv .venv/
source .venv/bin/activate
# install the dependency
python3 -m pip install "fastapi[standard]"

Then run the server with:

Terminal window
fastapi dev main.py

N.B.: You could also use a Docker or Podman container.

The project structure is:

  • Directoryuser-crud
    • Directoryrouters/ expose API endpoint
    • Directoryschemas/ implement models
    • Directoryservices/ implement business logic
    • main.py include routes

Here is a list of API calls based on the OS you’re using. If you prefer a graphical way to perfom API calls, I suggest you to use Postman application.

POST

Windows PowerShell
curl -Method POST http://localhost:8000/users `
-Headers @{ "Content-Type" = "application/json" } `
-Body '{ "name": "John", "age": 18 }'

GET by ID

Windows PowerShell
curl -Method GET http://localhost:8000/users/0

GET all

Windows PowerShell
curl -Method GET http://localhost:8000/users

UPDATE by ID

Windows PowerShell
curl -Method PUT http://localhost:8000/users/0 `
-Headers @{ "Content-Type" = "application/json" } `
-Body '{ "name": "New Name", "age": 18 }'

DELETE by ID

Windows PowerShell
curl -Method DELETE http://localhost:8000/users/0

FastAPI provides API documentation pages out of the box.

Or, if you prefer, you can also take a look at:

Here you are with your first CRUD API application written with FastAPI!

Links related to this article: