참고 : 초보자를 위한 FastAPI 과정 - YouTube
from fastapi import FastAPI
from fastapi import Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
students = {
1: {
"name":"John",
"age":17,
"year":"year 12"
}
}
class Student(BaseModel):
name: str
age: int
year: str
class UpdateStudent(BaseModel):
name: Optional[str] = None
age: Optional[int] = None
year: Optional[str] = None
@app.get("/")
def index():
return {"message": "First Data"}
# path parameter
@app.get("/get-student/{student_id}")
def get_student(student_id: int):
return students[student_id]
# query parameter
# ex) google.com/results?search=Python
@app.get("/get-by-name")
def get_student(*, name: Optional[str] = None, test: int):
for student_id in students:
if students[student_id]["name"] == name:
return students[student_id]
return {"Data": "Not Found"}
# combine query parameter & path parameter
@app.get("/get-by-name/{student_id}")
def get_student(*, student_id: int, name: Optional[str] = None, test: int):
for sid in students:
if students[sid]["name"] == name:
return students[sid]
return {"Data": "Not Found"}
@app.post("/create-student/{student_id}")
def create_student(student_id: int, student: Student):
if student_id in students:
return {"Error": "Student already exists"}
students[student_id] = student
return students[student_id]
@app.put("/update-student/{student_id}")
def update_student(student_id: int, student: UpdateStudent):
if student_id not in students:
return {"Error": "Student does not exist"}
if student.name != None:
students[student_id].name = student.name
if student.age != None:
students[student_id].age = student.age
if student.year != None:
students[student_id].year = student.year
return students[student_id]
@app.delete("/delete-student/{student_id}")
def delete_student(student_id: int):
if student_id not in students:
return {"Error": "student does not exist"}
del students[student_id]
return {"message": "Student deleted"}
> uvicorn myapi:app --reload
INFO: Will watch for changes in these directories: ['C:\\Users\\enkee\\OneDrive\\바탕 화면\\2023\\CS\\fastAPI']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [3368] using statreload
WARNING: The --reload flag should not be used in production on Windows.
INFO: Started server process [9808]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:2159 - "GET / HTTP/1.1" 200 OK
INFO: 127.0.0.1:2159 - "GET /favicon.ico HTTP/1.1" 404 Not Found
'Computer Science > BackEnd' 카테고리의 다른 글
Docker compose로 Django, Nginx, Mysql 띄우기 (0) | 2023.06.22 |
---|---|
에러 해결 | ‘bash\r’: No such file or directory 해결하기 (0) | 2023.04.18 |
[에러 해결] AttributeError: WebDriver object has no atribute find_element_by_class (0) | 2023.03.27 |
장고에서 Gunicorn 사용하기 | 장고 공식 문서 번역 (0) | 2022.11.25 |
장고 WSGI를 이용하여 배포하기 | 장고 공식 문서 번역 (0) | 2022.11.25 |