본문 바로가기
Python/Fast Api

01. Fast API

by 사라리24 2024. 6. 4.
SMALL

 

1. Fast API

  FastAPI는 Python 기반의 웹 프레임워크로, 주로 API를 빠르게 개발하기 위해 설계되었습니다. FastAPI는 강력한 타입 힌팅(Type Hints)을 활용하여 개발자에게 코드 작성의 안정성과 가독성을 제공합니다.

 

 

FastAPI

FastAPI framework, high performance, easy to learn, fast to code, ready for production

fastapi.tiangolo.com

 

 

  • Fast API 설치
  
 
            pip install fastapi
 
 
 

 

  • setting에서 설치하는 방법
더보기

 

 

 

  • Fast API 사용하기
  
 
 
            from fastapi import FastAPI
 
 
 

 

  • 참고
더보기


  타입 힌팅(Type Hints)

타입 힌팅(Type Hints)은 프로그래밍 언어에서 변수, 함수 매개변수, 함수 반환값 등에 대한 데이터 타입 정보를 코드에 명시적으로 제공하는 기술입니다.
Python 3.5 이상에서 도입된 기능으로, 코드의 가독성을 높이고 프로그램의 안정성을 강화하는 데 도움이 됩니다.

※ ASGI 서버

ASGI는 Asynchronous Server Gateway Interface의 약자로, 비동기 웹 애플리케이션과 서버 간의 표준 인터페이스를 제공하는 프로토콜입니다. ASGI는 Python 웹 애플리케이션을 구축할 때 비동기 처리를 지원하고, 실시간 기능을 구현할 수 있도록 하는 중간 계층 역할을 합니다.

기존의 WSGI(웹 서버 게이트웨이 인터페이스)는 동기적인 요청과 응답을 다루는 데에 효과적이었습니다. 하지만 현대의 웹 애플리케이션에서는 동시성(concurrency)이나 비동기(asynchronous) 처리가 중요한 역할을 하게 되면서 WSGI의 한계가 드러나게 되었습니다.

 

  • 설치
  
 
              # Windows
              python -m venv 가상환경이름
 
              # macOS/Linux
              python3 -m venv 가상환경이름
 
 
  
FastAPI를 설치하기 전에 Python 가상환경을 만들어줍니다.
가상환경을 사용하면 프로젝트 간에 의존성 충돌을 방지하고 프로젝트 별로 필요한 패키지를 독립적으로 관리할 수 있습니다.

 

 

  • 가상환경을 활성화
 
 
          # Windows
          venv\Scripts\activate
 
          # macOS/Linux
          source venv/bin/activate
 
 
  
가상환경이 생성되면 해당 가상환경을 활성화합니다.

 

 

 

  •  uvicorn이라는 ASGI 서버 설치
 
 
         pip install "uvicorn[standard]"
 
 

 

 

 

  • 실행
 
 
 
      uvicorn main:app --reload
 
 
  

 

 

  • get(1)

 

더보기

 

 
 
 
              # pip install fastapi
              # setting > projectName(자신의 프로젝트 폴더) > interpreter > fastapi 검색 후 설치
              from fastapi import FastAPI
              from pydantic import BaseModel
              from typing import Optional

              app = FastAPI()

              users = {
                  0: {"userid": "apple", "name": "김사과"},
                  1: {"userid": "banana", "name": "반하나"},
                  2: {"userid": "orange", "name": "오렌지"},
                  3: {"userid": "cherry", "name": "체리"},
              }


              # http://127.0.0.1:8000/
              @app.get('/')
              async def root():
                  return {"message": "Hello FastAPI!"}
 
 
 
 
 

 

  • get(2)








더보기
 
     
              # http://127.0.0.1:8000/users/1
              @app.get("/users/{id}")
              async def find_user(id: int):  # 비동기 이유
                  user = users[id]
                  return user

              # http://127.0.0.1:8000/users/1/userid
              # http://127.0.0.1:8000/users/1/name
              @app.get("/users/{id}/{key}")
              async def find_user_by_key(id: int, key: str):
                  userid = users[id][key]
                  return userid
 
 

 

 

 

 

  • post
 












-------------------------------------------------------------------------------------------------------------------------------------------------------------------








------------------------------------------------------------------------------------------------------------------------------------------------------------------




 

더보기

  

 
              class User(BaseModel):
                  userid: str
                  name: str

              # http:127.0.0.1:8000/users/10
              @app.post("/users/{id}")
              async def create_user(id: int, user: User):
                  if id in users:
                      return {"error": "이미 존재하는 키"}
                  users[id] = user.__dict__
                  return {"success": "ok"}

              class UserForUpdate(BaseModel):
                  userid: Optional[str]
                  name: Optional[str]
 
  
 

 

 

  • put / delete
 

더보기
 
 
 
              # 수정
              # id를 입력받아 id가 존재하지 않으면 에러
              # userid가 존재하면 userid를 변경
              # name이 존재하며 name을 변경
              @app.put("/users/{id}")
              async def update_user(id: int, user: UserForUpdate):
                  if id not in users:
                      return {"error": "id가 존재하지 않음"}
                  if user.userid:
                      users[id]['userid'] = user.userid
                  if user.name:
                      users[id]['name'] = user.name

                  return {"success": "ok"}


              #삭제
              @app.delete("/users/{id}")
              def delete_item(id: int):
                  users.pop(id)
                  return {"success": "ok"}
              # id를 입력받아 id가 존재하면 삭제
 
 
 

 

 

 

'Python > Fast Api' 카테고리의 다른 글

03. ChatGPT  (1) 2024.06.04
02. Streamlit  (0) 2024.06.04