AI 공부 도전기

Beginner를 위한 FastAPI Course (freeCodeCamp 채널 영상 요약)

 

     

 

 

 

 

 

https://fastapi.tiangolo.com/ko/

 

FastAPI

FastAPI FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준비된 프로덕션 문서: https://fastapi.tiangolo.com 소스 코드: https://github.com/tiangolo/fastapi FastAPI는 현대적이고, 빠르며(고성능), 파이썬

fastapi.tiangolo.com

 

시작 전 package 설치

 

pip install fastapi

pip install uvicorn

 

실험 예제 1

 

Python

 

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"}

 

Command

 

uvicorn myapi:app --reload

 

URL

 

홈페이지에 위 command에서 제공하는 URL 사용하여 접속

 

http://127.0.0.1:8000

http://127.0.0.1:8000/docs

 

실험 예제 2

 

Python

 

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]

 

URL

 

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 출력

 

 

Path Parameter

 

Python

 

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]

 

URL

 

0보다 작거나 3보다 크도록 숫자를 설정하면 Error

1을 설정하면 표시

 

그러나 2를 설정해도 student에는 없기때문에 error 발생

 

 

 

Query Parameter

 

Python

 

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"}

 

URL

 

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"}

 

Request Body and The Post Method

 

Python

 

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]

 

URL

 

student_id를 새로 넣고 Request body를 채운 다음 Execute 진행

 

 

이후 위에서 만든 get-student를 통해 확인 : 잘 실행됨.

 

 

 

 

Put Method 1

 

 

Python

 

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]

 

URL

이름만 기입시 나머지 Null로 설정됨

 

Put Method 2

 

Python

 

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]

 

 

URL

age만 바꿔도 나머지 값들은 잘 설정됨을 확인할 수 있음

 

 

Delete Method

 

 

Python

 

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"}

 

 

URL

 

 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading