Skip to content

Instantly share code, notes, and snippets.

@mjtiempo
Created December 8, 2022 15:55
Show Gist options
  • Select an option

  • Save mjtiempo/b97d973ebeb31d1154fada2268a71b60 to your computer and use it in GitHub Desktop.

Select an option

Save mjtiempo/b97d973ebeb31d1154fada2268a71b60 to your computer and use it in GitHub Desktop.

Revisions

  1. mjtiempo created this gist Dec 8, 2022.
    52 changes: 52 additions & 0 deletions fast_api_crud_orm.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    '''
    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}