Skip to content
Snippets Groups Projects

add new enpoint

parent 2b8fdfa1
No related branches found
No related tags found
No related merge requests found
import requests
url = "http://127.0.0.1:8000/users/"
data = {
"username": "john_doe",
"password": "password123",
"email": "john@example.com",
"phone_number": "1234567890"
# Add other fields as needed
}
response = requests.post(url, json=data)
print(response.status_code)
print(response.json())
\ No newline at end of file
File added
from enum import Enum
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException, Path, Query
from typing import Union
app = FastAPI()
class Category(Enum):
TOOLS = "tools"
CONSUMABLES = "consumables"
class Item(BaseModel):
name: str
price: float
count: int
id: int
category: Category
items = {
0: Item(name="Hammer", price=9.99, count=20, id=0, category=Category.TOOLS),
1: Item(name="Pliers", price=5.99, count=20, id=1, category=Category.TOOLS),
2: Item(name="Nails", price=1.99, count=100, id=2, category=Category.CONSUMABLES),
}
@app.get("/")
def index() -> dict[str, dict[int, Item]]:
return {"items": items}
@app.get("/items/{item_id}")
def query_item_by_id(item_id: int) -> Item:
if item_id not in items:
HTTPException(status_code=404, detail=f"Item with {item_id=} does not exist.")
return items[item_id]
# Selection = dict[
# str, str | int | float | Category | None
# ] # dictionary containing the user's query arguments
Selection = dict[str, Union[str, int, float, Category, None]]
@app.get("/items/")
def query_item_by_parameters(
name: Union[str, None] = None,
price: Union[float, None] = None,
count: Union[int, None] = None,
category: Union[Category, None] = None,
) -> dict[str, Union[Selection, list[Item]]]:
def check_item(item: Item):
"""Check if the item matches the query arguments from the outer scope."""
return all(
(
name is None or item.name == name,
price is None or item.price == price,
count is None or item.count != count,
category is None or item.category is category,
)
)
selection = [item for item in items.values() if check_item(item)]
return {
"query": {"name": name, "price": price, "count": count, "category": category},
"selection": selection,
}
@app.post("/")
def add_item(item: Item) -> dict[str, Item]:
if item.id in items:
HTTPException(status_code=400, detail=f"Item with {item.id=} already exists.")
items[item.id] = item
return {"added": item}
# We can place further restrictions on allowed arguments by using the Query and Path classes.
# In this case we are setting a lower bound for valid values and a minimal and maximal length for the name.
@app.put("/update/{item_id}")
def update(
item_id: int = Path(ge=0),
name: Union[str , None] = Query(defaut=None, min_length=1, max_length=8),
price: Union[float, None] = Query(default=None, gt=0.0),
count: Union[int, None] = Query(default=None, ge=0),
):
if item_id not in items:
HTTPException(status_code=404, detail=f"Item with {item_id=} does not exist.")
if all(info is None for info in (name, price, count)):
raise HTTPException(
status_code=400, detail="No parameters provided for update."
)
item = items[item_id]
if name is not None:
item.name = name
if price is not None:
item.price = price
if count is not None:
item.count = count
return {"updated": item}
@app.delete("/delete/{item_id}")
def delete_item(item_id: int) -> dict[str, Item]:
if item_id not in items:
raise HTTPException(
status_code=404, detail=f"Item with {item_id=} does not exist."
)
item = items.pop(item_id)
return {"deleted": item}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment