# RESTful API FastAPI ## 安裝 ``` python pip install fastapi ``` ## 啟動 uvicorn main:app --reload --port 8000 讓Clinet可連用IP連線 uvicorn main:app --host 0.0.0.0 --port 8000 --reload ## RESTful API GET ### RESTful API GET 無參數(Hello world) #### GET Server (Hello world) ``` python from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} ``` #### GET Client (Hello world) http://127.0.0.1:8000  ### RESTful API GET 帶數字id&參數q #### GET Server (帶數字id&參數q) ``` python @app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} ```  #### GET Client (帶數字id&參數q) http://127.0.0.1:8000/items/1?q=6  ### RESTful API GET (帶數字id&兩個參數相加) #### GET Server (帶數字id&兩個參數相加) ``` python @app.get("/itemsTest/{Item_id}") async def create_item(Item_id: int, a: int, b: int): print("a+b = %d" ,a+b) return {"item_id": Item_id, "a+b": (a+b)} ```  #### GET Client (帶數字id&兩個參數相加) http://127.0.0.1:8000/itemsTest/1?a=6&b=5  ## RESTful API POST ### RESTful POST Server ``` python from pydantic import BaseModel from fastapi import FastAPI app = FastAPI() class Item(BaseModel): name: str description: str = None price: float tax: float = None @app.post("/items/{Item}") async def create_item(item: Item): print(item) return item ```  ### RESTful POST Client #### 安裝 必須pip install requests #### POST Client Jason傳值方式 ``` python from pydantic import BaseModel from fastapi import FastAPI app = FastAPI() def main(name): url = "http://127.0.0.1:8000/items/1" data = {"name": "test1", "price": 60} headers = {"Content-Type": "application/json"} response = requests.post(url, data=json.dumps(data), headers=headers) ```  #### 回傳結果  ## FastAPI error 顯示 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up