1 |
6c1e92e3
|
Matej Zeman
|
from typing import List
|
2 |
|
|
|
3 |
|
|
from fastapi import Depends, FastAPI, HTTPException, APIRouter
|
4 |
|
|
from sqlalchemy.orm import Session
|
5 |
ef87a1d2
|
Matej Zeman
|
from sql_app import crud, models, schemas
|
6 |
6c1e92e3
|
Matej Zeman
|
from ..database import SessionLocal, engine
|
7 |
|
|
|
8 |
|
|
models.Base.metadata.create_all(bind=engine)
|
9 |
|
|
|
10 |
4911f0ea
|
Matej Zeman
|
# prefix used for all endpoints in this file
|
11 |
2229e0e1
|
Matej Zeman
|
device = APIRouter(prefix="/api/v1")
|
12 |
6c1e92e3
|
Matej Zeman
|
|
13 |
4911f0ea
|
Matej Zeman
|
|
14 |
6c1e92e3
|
Matej Zeman
|
# Dependency
|
15 |
|
|
def get_db():
|
16 |
|
|
db = SessionLocal()
|
17 |
|
|
try:
|
18 |
|
|
yield db
|
19 |
|
|
finally:
|
20 |
|
|
db.close()
|
21 |
|
|
|
22 |
|
|
|
23 |
2229e0e1
|
Matej Zeman
|
@device.post("/device", response_model=schemas.Device)
|
24 |
6c1e92e3
|
Matej Zeman
|
def create_device(device: schemas.DeviceCreate, db: Session = Depends(get_db)):
|
25 |
4911f0ea
|
Matej Zeman
|
"""
|
26 |
|
|
Endpoint used for creating new device
|
27 |
|
|
"""
|
28 |
6c1e92e3
|
Matej Zeman
|
print(crud.create_device(db=db, device=device))
|
29 |
|
|
|
30 |
|
|
|
31 |
2229e0e1
|
Matej Zeman
|
@device.get("/devices", response_model=List[schemas.Device])
|
32 |
6c1e92e3
|
Matej Zeman
|
def read_devices(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
33 |
4911f0ea
|
Matej Zeman
|
"""
|
34 |
|
|
Endpoint returns all devices in database
|
35 |
|
|
"""
|
36 |
6c1e92e3
|
Matej Zeman
|
devices = crud.get_devices(db, skip=skip, limit=limit)
|
37 |
|
|
return devices
|
38 |
|
|
|
39 |
|
|
|
40 |
|
|
@device.get("/device/{device_id}", response_model=schemas.Device)
|
41 |
|
|
def read_device(device_id: int, db: Session = Depends(get_db)):
|
42 |
4911f0ea
|
Matej Zeman
|
"""
|
43 |
|
|
Returns one specific device by given id
|
44 |
|
|
"""
|
45 |
6c1e92e3
|
Matej Zeman
|
db_device = crud.get_device(db, device_id=device_id)
|
46 |
|
|
if db_device is None:
|
47 |
|
|
raise HTTPException(status_code=404, detail="Device not found")
|
48 |
|
|
return db_device
|