> For the complete documentation index, see [llms.txt](https://go.raymondctw.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://go.raymondctw.dev/technology/web-development/fastapi.md).

# FastAPI

FastAPI是一個較晚推出且快速成為社群討論焦點的Python後端框架，整體架構與Flask相似，如果你是Flask使用者將能夠無痛轉換，FastAPI有以下特點：

* 自動產生互動式API文件
* 非同步處理(Asynchronize)
* 資料驗證
* WebSocket

## 1. 安裝FastAPI

```
pip install fastapi 
pip install uvicorn[standard]
```

## 2. 建立FastAPI應用程式

FastAPI的基本架構與Flask相當類似。

{% code title="main.py" %}

```python
from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def read_root():
    return {"Hello": "This is FastAPI!"}

```

{% endcode %}

## 3. 執行FastAPI應用程式

FastAPI的啟動方式與Flask有些不同，必須使用uvicorn來執行，在Terminal上執行以下：

```
uvicorn main:app --reload
```

* main：FastAPI主程序檔案，如上面範例的`main.py`
* app：`main.py` 中app物件

成功執行後將會出現以下資訊，即可於`http://127.0.0.1:8000` 進行測試。

```
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28720]
INFO:     Started server process [28722]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
```

如果想類似於Flask直接執行此`*.py` 則可以用以下方法：

```python
from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get('/')
def read_root():
    return {"Hello": "This is FastAPI!"}
    
if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)
```
