FastAPI

main.py

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Union

app = FastAPI()
items = [“one”,”two”,”three”,”four”]

class Item(BaseModel):
name: str
price: float
description: Union[str, None] = None

@app.get(“/”)
def read_root():
return {“message”: “Hello world!!”}

@app.get(“/items”)
def read_items(skip: int = 0, limit: int = 10):
return {“items”: items[skip : skip + limit]}

@app.post(“/items/”)
def create_item(item: Item):
print(f”データを登録します: {item.name}, {item.price}, {item.description}”)
return item

client.py

import requests

res = requests.get(“http://127.0.0.1:8000/items/”)

res = requests.post(
“http://127.0.0.1:8000/items/”,
json={“name”:”Tシャツ”, “price”: 2000, “description”: “白Tシャツ”},
)

print(res.status_code)
print(res.text)

python -m uvicorn main:app –reload

http://127.0.0.1:8000/

Leave a Reply

Your email address will not be published. Required fields are marked *