Python (with. Code)/FastAPI 8

[FastAPI] (8) API Router 사용하기

API Router 사용하기 API Endpoints를 여러 .py 파일에 분리하여 작성하기 위한 APIRouter 라는 모듈이 존재한다. 해당 모듈을 사용하면 큰 갈래의 API들 끼리는 묶어 관리를 편하게 할 수 있다. 📁 Folder Structure ├── router │ ├── router_1.py // health check router │ └── router_2.py // servic1 router └── app.py Router 분기 작성 app.py에 router를 추가하고, prefix, tags 등을 설정한다. 🛠 app.py import uvicorn from fastapi import FastAPI from routers.router_1 import router as health_r..

[FastAPI] (7) MySQL 연결 및 API Test

MySQL 설치 및 DB 생성 1-1. MySql 설치 (로컬 pc에 직접 설치) https://www.mysql.com/downloads/ MySQL :: MySQL Downloads MySQL Cluster CGE MySQL Cluster is a real-time open source transactional database designed for fast, always-on access to data under high throughput conditions. MySQL Cluster MySQL Cluster Manager Plus, everything in MySQL Enterprise Edition Learn More » C www.mysql.com 1-2. Docker MySQL 설치 doc..

[FastAPI] (6) 보일러 플레이트 (Boiler Plate)

BoilerPlate란? BoilerPlate Code란 재 사용할 수 있는 뼈대 코드로, 보일러 플레이트를 작성해 놓고, 프로젝트 신규 생성 시마다 적용하여 사용 가능하다. 폴더 구조 FastAPI BoilerPlate ┌─FastAPI BoilerPlate │ └─deployments │ │ │ └─ Dockerfile ├─src │ ├─app.py : 최초 main 실행 함수 │ │ │ ├─dtos/ : Input, Output 전달 Object │ │ │ ├─db/ : DB Connect and CRUD │ │ │ ├─models/ : DB models │ │ │ ├─router/ : API Router │ │ │ ├─services/ : 비즈니스 로직 서비스 │ │ │ └─test/ : 모듈별 ..

[FastAPI] (5) FastAPI Validation - Path, Query, Field

Path, Query, Field Pydantic의 데이터 검증에 덧붙여 FastAPI의 Field, Path, Query를 사용해 매개변수를 명시적으로 정의하고, 좀더 세부적인 데이터 검증이 가능하다. gt, ge, lt, le : 숫자 대소비교 (greater than, less than 등) min_length, max_length : 문자열 길이 값 min_items, max_items : List, Set등의 Collection 객체 담당 regex 등 도 사용 가능 방법에는 크게 2가지가 존재 함수 인자에서 FastAPI의 Path, Query를 활용하는 방법 BaseModel을 상속한 Class에서 Pydantic의 Field 사용 방법 예제 공통 부분 - 임의 데이터셋 생성 예제 1과 예제..

[FastAPI] (4) FastAPI POST 작성법

POST Method FastAPI 에서 POST Method는 다음과 같은 특징이 있다. Schema Dependency가 존재한다. (Pydantic) BaseModel을 상속 받은 객체로 인자를 넘겨 받아야 한다. POST Method 예제 1 Pydantic의 이메일 (EmailStr), 파일 경로, 우편 번호, URL(HttpURL) 를 사용하면 다양한 형태의 값을 쉽게 검증 가능 from fastapi import FastAPI, status from pydantic import BaseModel, HttpUrl from typing import Optional app = FastAPI() class User(BaseModel): name:str url:Optional[HttpUrl] = No..

[FastAPI] (3) FastAPI 열거형 enum - GET

Enum이란? 열거형 (Enumeration) 객체로, Python 에서 Query Parameters, Path Parameters에 대한 Entity 정의를 하기 위해 사용 Case 1 from enum import Enum class Score(str, Enum): A="A" B="B" C="C" @app.get("/grade") def get_grade(score:Score): return {"score":score} 요청 1) curl localhost:8000/grade?score=A => { "score":A } 반환 요청 2) curl localhost:8000/grade => 422 entity error 발생 요청 3) curl localhost:8000/grade?score=D => ..

[FastAPI] (2) FastAPI 경로 매개변수, 쿼리 매개변수 - GET

경로 매개변수란? 경로 매개변수(Path Parameters)란 URL 경로에 들어가는 변수를 의미 아래 예시에서의 user_id를 뜻함 (매개 : 넘겨주는 + 변수 : 변하는 값) Case 1 @app.get("/users/{user_id}") def get_user(user_id:int): return {"user_id":user_id} 요청 1) curl localhost:8000/users/3 => { "user_id":3 } 반환 요청 2) curl localhost:8000/users/3.4 => 422 entity error 발생 (type 안맞아서 발생하는 error) Case 2 @app.get("/users/{user_id}/{art_id}") def get_user(user_id:in..

[FastAPI] (1) FastAPI란? (+Setting)

Fast API 란? FastAPI - https://fastapi.tiangolo.com/ FastAPI FastAPI FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fastapi.tiangolo.com Source Code: https://github.com/tiangolo/fastapi FastAPI is a modern, fast (high-performance), web framework for buil fastapi.tiangolo.com 코어 시스템 (Starlette) Wrapping을 통한 ASGI 지원과, Pydantic을 통한 간편한 유..