What is FastAPI?
According to its official website,
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.
Hello World with FastAPI
Installation
Requirements
Python3.8+
Install FastAPI
|
|
Install ASGI Server
|
|
Define a FastAPI app
Create a file main.py with:
|
|
Create API Endpoints
In main.py add the following 2 endpoints implementation
|
|
API Endpoints with Automatic Validation
final code looks like this:
|
|
Test
Run the server with
|
|
INFO: Will watch for changes in these directories: [’/Users/xxx/PycharmProjects/pythonProject’]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [99265] using WatchFiles
INFO: Started server process [99267]
INFO: Waiting for application startup.
INFO: Application startup complete.
Open it in the browser and test the endpoints defined above.
API Documentation
FastAPI has interactive API docs built-in by default.
Interactive Docs Powered by Swagger UI
Go to /docs, we can the interactive API docs:
Automatic API doc with ReDoc
Go to /redoc, we can see another automatic API documentation:
General Thoughts
FastAPI is generally a lightweight framework to develop APIs with Python. Some attractive advantages of FastAPI for me compared to a comprehensive framework like Django:
- fast to set up; fast to build APIs, prototypes, and POCs
- automatic validation with Pydantic
- Automatic API docs
I would definitely consider FastAPI to be my first option if I want to test some ideas quick, and honest I think it’s also quite attractive to build production systems as well, given more and more web applications are single page applications with React, Vue, or Angular that only requires APIs from backend. Django is a little too heavy for such case