|
| 1 | +from typing import List |
| 2 | +from fastapi import FastAPI, HTTPException |
| 3 | + |
| 4 | +from app.models import Product |
| 5 | + |
| 6 | +# run: fastapi dev app\main.py |
| 7 | + |
| 8 | +app = FastAPI() |
| 9 | +products = [Product(id=1, name="product_1", price=100.00)] |
| 10 | + |
| 11 | + |
| 12 | +@app.get("/", response_model=dict) |
| 13 | +def read_root(): |
| 14 | + """ |
| 15 | + read root |
| 16 | + """ |
| 17 | + return {"message": "Products API!"} |
| 18 | + |
| 19 | + |
| 20 | +@app.get("/products", response_model=List[Product]) |
| 21 | +def get_products(): |
| 22 | + """ |
| 23 | + get all products |
| 24 | + """ |
| 25 | + return products |
| 26 | + |
| 27 | + |
| 28 | +@app.get("/products/{product_id}", response_model=Product) |
| 29 | +def get_product(product_id: int): |
| 30 | + """ |
| 31 | + get product by id |
| 32 | + """ |
| 33 | + for product in products: |
| 34 | + if product.id == product_id: |
| 35 | + return product |
| 36 | + raise HTTPException(status_code=404, detail="Product not found") |
| 37 | + |
| 38 | + |
| 39 | +@app.post("/products", response_model=Product) |
| 40 | +def create_product(product: Product): |
| 41 | + """ |
| 42 | + create product |
| 43 | + """ |
| 44 | + max_product_id = max(prod.id for prod in products) |
| 45 | + product.id = max_product_id + 1 |
| 46 | + products.append(product) |
| 47 | + return product |
| 48 | + |
| 49 | + |
| 50 | +@app.put("/products/{product_id}", response_model=Product) |
| 51 | +def update_product(product_id: int, updated_product: Product): |
| 52 | + """ |
| 53 | + update product |
| 54 | + """ |
| 55 | + for index, product in enumerate(products): |
| 56 | + if product.id == product_id: |
| 57 | + updated_product.id = product_id |
| 58 | + products[index] = updated_product |
| 59 | + return updated_product |
| 60 | + raise HTTPException(status_code=404, detail="Product not found") |
| 61 | + |
| 62 | + |
| 63 | +@app.delete("/products/{product_id}", response_model=Product) |
| 64 | +def delete_product(product_id: int): |
| 65 | + """ |
| 66 | + delete product |
| 67 | + """ |
| 68 | + for index, product in enumerate(products): |
| 69 | + if product.id == product_id: |
| 70 | + return products.pop(index) |
| 71 | + raise HTTPException(status_code=404, detail="Product not found") |
0 commit comments