https://fastapi.tiangolo.com/ko/
pip install fastapi
pip install uvicorn
from fastapi import FastAPI
app = FastAPI()
"""
GET - Get an information
POST - Create something new
PUT - update
DELETE - delete something
"""
@app.get("/")
def index():
return {"name": "First Data"}
uvicorn myapi:app --reload
홈페이지에 위 command에서 제공하는 URL 사용하여 접속
http://127.0.0.1:8000
http://127.0.0.1:8000/docs
from fastapi import FastAPI
app = FastAPI()
"""
GET - Get an information
POST - Create something new
PUT - update
DELETE - delete something
"""
students = {
1: {
"name": "john",
"age": 17,
"class": "Year 12"
}
}
@app.get("/")
def index():
return {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(student_id: int):
return students[student_id]
1)
# 직접적으로 student_id를 1로 넣음으로써 페이지를 획득
http://127.0.0.1:8000/get-student/1
2)
# docs
http://127.0.0.1:8000/docs
GET /get-student/{student_id}에서 "Try it out" 클릭 후 student_id에 값을 넣음
지금 설정상 1만 있으므로 1을 넣으면 아래와 같이 나옴
그러나 1 이외의 값을 넣으면 Internal Server Error 출력
0보다 크고 3보다 작은 student_id를 넣어야만 하도록 설정
from fastapi import FastAPI, Path
app = FastAPI()
"""
GET - Get an information
POST - Create something new
PUT - update
DELETE - delete something
"""
students = {
1: {
"name": "john",
"age": 17,
"class": "Year 12"
}
}
@app.get("/")
def index():
return {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(student_id: int = Path(None, description="The ID of the student you want to view", gt=0, lt=3)):
return students[student_id]
0보다 작거나 3보다 크도록 숫자를 설정하면 Error
1을 설정하면 표시
그러나 2를 설정해도 student에는 없기때문에 error 발생
from fastapi import FastAPI, Path
app = FastAPI()
"""
GET - Get an information
POST - Create something new
PUT - update
DELETE - delete something
"""
students = {
1: {
"name": "john",
"age": 17,
"class": "Year 12"
}
}
@app.get("/")
def index():
return {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(student_id: int = Path(None, description="The ID of the student you want to view", gt=0, lt=3)):
return students[student_id]
@app.get("/get-by-name")
def get_student(name: str):
for student_id in students:
if students[student_id]["name"] == name:
return students[student_id]
return {"Data": "Not found"}
students에 있는 name을 찾을 때 해당 id의 값들을 반환함.
만약 없다면 발견하지 못했다는 것을 반환
해당 함수가 필수가 아니도록 설정하기 위해서 Optional을 기입할 수도 있음
단, 필수로 기입해야 하는 파라미터는 Optional 앞에 적어야함.
from fastapi import FastAPI, Path
from typing import Optional
app = FastAPI()
"""
GET - Get an information
POST - Create something new
PUT - update
DELETE - delete something
"""
students = {
1: {
"name": "john",
"age": 17,
"class": "Year 12"
}
}
@app.get("/")
def index():
return {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(student_id: int = Path(None, description="The ID of the student you want to view", gt=0, lt=3)):
return students[student_id]
@app.get("/get-by-name")
def get_student(*, name: Optional[str] = None):
for student_id in students:
if students[student_id]["name"] == name:
return students[student_id]
return {"Data": "Not found"}
student 형식에 맞는 class를 만들고 create_student 함수를 통해 Create를 진행
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
"""
GET - Get an information
POST - Create something new
PUT - update
DELETE - delete something
"""
students = {
1: {
"name": "john",
"age": 17,
"year": "Year 12"
}
}
class Student(BaseModel):
name: str
age: int
year: str
@app.get("/")
def index():
return {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(student_id: int = Path(None, description="The ID of the student you want to view", gt=0, lt=3)):
return students[student_id]
@app.get("/get-by-name")
def get_student(*, name: Optional[str] = None):
for student_id in students:
if students[student_id]["name"] == name:
return students[student_id]
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 exists"}
students[student_id] = student
return students[student_id]
student_id를 새로 넣고 Request body를 채운 다음 Execute 진행
이후 위에서 만든 get-student를 통해 확인 : 잘 실행됨.
Put을 사용하여 Update 진행
UpdateStudent class를 만들어 Optional하도록 설정
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
"""
GET - Get an information
POST - Create something new
PUT - update
DELETE - delete something
"""
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 {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(student_id: int = Path(None, description="The ID of the student you want to view", gt=0, lt=3)):
return students[student_id]
@app.get("/get-by-name")
def get_student(*, name: Optional[str] = None):
for student_id in students:
if students[student_id]["name"] == name:
return students[student_id]
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 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"}
students[student_id] = student
return students[student_id]
이름만 기입시 나머지 Null로 설정됨
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
"""
GET - Get an information
POST - Create something new
PUT - update
DELETE - delete something
"""
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 {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(student_id: int = Path(None, description="The ID of the student you want to view", gt=0, lt=3)):
return students[student_id]
@app.get("/get-by-name")
def get_student(*, name: Optional[str] = None):
for student_id in students:
if students[student_id]["name"] == name:
return students[student_id]
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 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]
age만 바꿔도 나머지 값들은 잘 설정됨을 확인할 수 있음
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
"""
GET - Get an information
POST - Create something new
PUT - update
DELETE - delete something
"""
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 {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(student_id: int = Path(None, description="The ID of the student you want to view", gt=0, lt=3)):
return students[student_id]
@app.get("/get-by-name")
def get_student(*, name: Optional[str] = None):
for student_id in students:
if students[student_id]["name"] == name:
return students[student_id]
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 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 successfully"}