Skip to main content

FastAPI

Introduction

FastAPI is a modern, high-performance web framework for building APIs using Python. Designed with efficiency and developer productivity in mind, it takes full advantage of Python’s type hints to provide automatic validation, serialization, and robust error handling. FastAPI is particularly well-suited for building RESTful APIs, microservices, and backend services for real-time applications.

Core Features

  • Asynchronous Programming
  • Automatic Interactive API Documentation
  • Type-Driven Development
  • Data Validation with Pydantic
  • Built-in Dependency Injection
  • Security and Authentication
Tutorials

PyImageSearch

Getting Started

Installation
  • Installs FastAPI, the framework we’ll use to build our APIs.
  • Installs Uvicorn, the Asynchronous Server Gateway Interface (ASGI) that will run the FastAPI app and serve it to clients.
  • Installs PyTest, a testing framework that allows us to write and run test cases for our FastAPI endpoints efficiently.
pip install fastapi uvicorn pytest

Verify the installation

python -m uvicorn --help

Running a Basic Server

main.py: (NOTE: 檔名不能是檔名不能與專案名相同,例如 fastapi.py)

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}

Start the Server

uvicorn main:app --reload

Access the Application

http://127.0.0.1:8000/