본문 바로가기
프로그래밍 언어/Python

Python FastAPI 로 간단한 Rest API 만들어 보기

by 8호선방랑자 2022. 1. 18.

안녕하세요 데브윤 입니다 😄

오늘은 Python 으로 간단하게 Rest API를 개발 할 수 있는 FastAPI 프레임 워크를 소개 하려고 합니다.

🔎개발 환경


  • python 3.9.4
  • poetry (Dependency Management)
  • uvicorn (ASGI Server)
  • fastapi

🦈시작하기


Python 패키지 설치

  • fastapi 는 python3.6 버전 이상부터 사용가능합니다
  • 그리고 의존성 관리를 위해 poetry 도 설치 합니다
 $ curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -
  • poetry init
 # 패키지를 생성 fastapi_getting_started
 $ poetry init
 Package name [fastapi_get_started]:  fastapi_getting_started
 Version [0.1.0]:  0.1.0
 Description []:  fastapi beginner - devyoon91 blog 
 Author [devyoon91 <kimbyungyoun91@gmail.com>, n to skip]:  devyoon91
 License []:  
 Compatible Python versions [^3.9]:  
 ...

 # add 명령어로 fastapi 패키지 설치 
 $ poetry add fastapi

 # add 명령어로 uvicorn 패키지 설치
 $ poetry add uvicorn
  • pyproject.toml 생성 확인
 [tool.poetry]
 name = "fastapi_getting_started"
 version = "0.1.0"
 description = "fastapi beginner - devyoon91 blog"
 authors = ["devyoon91"]

 [tool.poetry.dependencies]
 python = "^3.9"
 fastapi = "^0.72.0"
 uvicorn = "^0.17.0"

 [tool.poetry.dev-dependencies]

 [build-system]
 requires = ["poetry-core>=1.0.0"]
 build-backend = "poetry.core.masonry.api"
  • poetry install
 $ poetry install
 $ poetry show
 anyio             3.5.0  High level compatibility layer for multiple asynchronous event loop implementations
 asgiref           3.4.1  ASGI specs, helper code, and adapters
 click             8.0.3  Composable command line interface toolkit
 colorama          0.4.4  Cross-platform colored terminal text.
 fastapi           0.72.0 FastAPI framework, high performance, easy to learn, fast to code, ready for production
 h11               0.12.0 A pure-Python, bring-your-own-I/O implementation of HTTP/1.1
 idna              3.3    Internationalized Domain Names in Applications (IDNA)
 pydantic          1.9.0  Data validation and settings management using python 3.6 type hinting
 sniffio           1.2.0  Sniff out which async library your code is running under
 starlette         0.17.1 The little ASGI library that shines.
 typing-extensions 4.0.1  Backported and Experimental Type Hints for Python 3.6+
 uvicorn           0.17.0 The lightning-fast ASGI server.

main.py 파일 생성

  • 아래와 같이 py 파일을 생성하고 FastAPI를 임포트 하면 간단하게 API 작성이 가능합니다.
  • $ vi main.py
 from fastapi import FastAPI

 app = FastAPI()

 @app.get("/")
 def hello_fastapi():
     return {"message": "hello world~!"}

 @app.get("/{doc_id}")
 def get_document_id(doc_id: int):
     return {"doc_id": doc_id}

uvicorn main.py 실행

📖참고


FastAPI

댓글