1+ from database import SessionLocal , engine , Base
2+ import models , schemas , crud
3+ from fastapi import FastAPI , Depends , HTTPException
4+ from sqlalchemy .orm import Session
5+
6+ models .Base .metadata .create_all (bind = engine )
7+ print ("Table is created" )
8+
9+ def get_db ():
10+ db = SessionLocal ()
11+ try :
12+ yield db
13+ finally :
14+ db .close ()
15+
16+ # Creating Routes
17+ app = FastAPI ()
18+
19+ @app .post ("/items/" , response_model = schemas .Item )
20+ def create_item (item : schemas .ItemCreate , db : Session = Depends (get_db )):
21+ return crud .create_item (db , item )
22+
23+ @app .get ("/items/" , response_model = list [schemas .Item ])
24+ def read_items (db : Session = Depends (get_db )):
25+ return crud .get_items (db )
26+
27+ @app .get ("/items/{item_id}" , response_model = schemas .Item )
28+ def read_item (item_id : int , db : Session = Depends (get_db )):
29+ item = crud .get_item (db , item_id )
30+ if not item :
31+ raise HTTPException (status_code = 404 , detail = "Item NOT FOUND" )
32+ return item
33+
34+ @app .put ("/items/{item_id}" , response_model = schemas .Item )
35+ def update_item (item_id : int , item : schemas .ItemCreate , db : Session = Depends (get_db )):
36+ updated_item = crud .update_item (db , item_id , item )
37+ if not updated_item :
38+ raise HTTPException (status_code = 404 , detail = "Item NOT FOUND" )
39+ return updated_item
40+
41+ @app .delete ("/items/{item_id}" )
42+ def delete_item (item_id : int , db : Session = Depends (get_db )):
43+ deleted_item = crud .delete_item (db , item_id )
44+ if not deleted_item :
45+ raise HTTPException (status_code = 404 , detail = "Item NOT FOUND" )
46+ return {"details" : "Deleted" }
47+
0 commit comments