Introduction to FastAPI
FastAPI is a modern Python web framework designed for building high-performance web APIs. Development is super fast and it automatically generates documentation (Yes! No more writing docs manually). To illustrate its speed, here’s a simple Web API in just 5 lines of code.
file name: test.py
1
2
3
4
5
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
return {"message": "Hello World! NBA 終於開打了!! 202310/25"} # it can return dict, list, str, int, etc.
Run it with the command uvicorn test1:app --reload
Features
Super Fast: FastAPI is built on the high-performance ASGI framework Starlette, enabling it to handle a large number of concurrent requests efficiently.
Powerful Type Hints: FastAPI utilizes Python 3.6+ type hints to define API endpoints, which results in well-documented code, autocomplete features, and static type checking.
Automatic Documentation Generation: FastAPI can automatically generate interactive documentation based on the type hints in your code, keeping your API documentation up-to-date and easy to navigate.
Authentication and Authorization: FastAPI supports common authentication and authorization methods such as Basic Auth, OAuth, JWT, etc., ensuring the security of your API.
cmd Demo
The following two files can be used to set up a FastAPI development environment in VSCode. Refer to this article for environment setup.
Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Use an official Python runtime as a parent image
FROM python:3.9-slim-buster
# Set the working directory to /app
WORKDIR /app
# Copy the requirements file into the container at /app
COPY requirements.txt .
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -r requirements.txt && \
rm -rf /root/.cache/pip/*
# Copy the rest of the application code into the container at /app
COPY . .
# Expose the port that Django runs on
EXPOSE 8000
requirement.txt
Wait, why include the uvicorn library? Because FastAPI doesn’t have a built-in development server. Using uvicorn provides benefits such as ASGI, hot reload, and multi-process support.
1
2
fastapi
uvicorn
Check out the automatically generated documentation at
1
http://127.0.0.1:8000/docs
This documentation is interactive, allowing you to call the API directly, check if the parameters are correct, and verify if the return values are as expected.
We will continue exploring FastAPI and see what applications we can develop.
We will see.