簡介、安裝、快速開始
## FastAPI 是什麼?
FastAPI 是 Python 的現代化 Web 框架,適合用來快速建立:
- RESTful API
- 後端服務
- 微服務
- 自動產生 API 文件
- 具備型別檢查與資料驗證的 API
它支援非同步處理,並會自動產生 Swagger UI 與 ReDoc 文件。
## 安裝
先確認已安裝 Python 3.8 以上,執行:
```bash
pip install fastapi uvicorn
```
## 5 行內基本程式
建立 `main.py`:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
```
## 啟動 FastAPI
在 `main.py` 所在資料夾執行:
```bash
uvicorn main:app --reload
```
其中:
- `main` 代表 `main.py`
- `app` 代表程式中的 FastAPI 物件
- `--reload` 會在程式修改後自動重新載入
## 測試成果
開啟瀏覽器前往:
```text
http://127.0.0.1:8000/
```
應會看到:
```json
{"message": "Hello, FastAPI!"}
```
也可以使用互動式 API 文件測試:
```text
http://127.0.0.1:8000/docs
```
或用命令列測試:
```bash
curl http://127.0.0.1:8000/
```
相關學習地圖、教學課程
Python 後端工程、資料庫