fapi/app/main.py

58 lines
1.6 KiB
Python

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from fastapi.middleware.cors import CORSMiddleware
from app.database import SessionLocal, engine
import app.models as models
from app.schemas import Person, PersonCreate
app = FastAPI()
origins = [
"http://localhost:8080",
"http://mpabi.pl:8888",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# Endpoint do tworzenia nowej osoby (POST)
@app.post("/persons/", response_model=Person)
def create_person(person: PersonCreate, db: Session = Depends(get_db)):
db_person = models.Person(
last_name=person.last_name,
first_name=person.first_name,
address=person.address,
city=person.city
)
db.add(db_person)
db.commit()
db.refresh(db_person)
return db_person
# Endpoint do odczytu listy osób (GET)
@app.get("/persons/", response_model=list[Person])
def read_persons(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
persons = db.query(models.Person).offset(skip).limit(limit).all()
return persons
# Endpoint do odczytu osoby po ID (GET)
@app.get("/persons/{person_id}", response_model=Person)
def read_person(person_id: int, db: Session = Depends(get_db)):
person = db.query(models.Person).filter(models.Person.person_id == person_id).first()
if person is None:
raise HTTPException(status_code=404, detail="Person not found")
return person