Created
December 8, 2022 15:55
-
-
Save mjtiempo/b97d973ebeb31d1154fada2268a71b60 to your computer and use it in GitHub Desktop.
FastAPI with CRUD using ORM SQLAchemy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Generated by ChatGPT using the prompt | |
fastapi crud using orm sqlalchemy | |
''' | |
from fastapi import FastAPI | |
from sqlalchemy import create_engine, Column, Integer, String | |
from sqlalchemy.orm import sessionmaker | |
app = FastAPI() | |
engine = create_engine("<database_url>") | |
Session = sessionmaker(bind=engine) | |
session = Session() | |
class Item(Base): | |
__tablename__ = "items" | |
id = Column(Integer, primary_key=True) | |
name = Column(String) | |
Base.metadata.create_all(engine) | |
@app.get("/") | |
async def get_all_items(): | |
items = session.query(Item).all() | |
return items | |
@app.post("/") | |
async def create_item(item: dict): | |
new_item = Item(**item) | |
session.add(new_item) | |
session.commit() | |
return {"id": new_item.id} | |
@app.put("/{id}") | |
async def update_item(id: int, item: dict): | |
item_to_update = session.query(Item).filter(Item.id == id).first() | |
if not item_to_update: | |
raise HTTPException(status_code=404, detail="Item not found") | |
item_to_update.update(**item) | |
session.commit() | |
return {"id": id} | |
@app.delete("/{id}") | |
async def delete_item(id: int): | |
item_to_delete = session.query(Item).filter(Item.id == id).first() | |
if not item_to_delete: | |
raise HTTPException(status_code=404, detail="Item not found") | |
session.delete(item_to_delete) | |
session.commit() | |
return {"id": id} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment