Last active
May 11, 2025 08:21
-
-
Save koorukuroo/02f8e3734365a53e3aff277e8a0b8768 to your computer and use it in GitHub Desktop.
Basic FastAPI App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import FastAPI | |
import redis | |
# FastAPI 앱 인스턴스 생성 | |
app = FastAPI( | |
title="Redis CRUD API", | |
description="FastAPI와 Redis를 이용한 간단한 Key-Value 저장소 API입니다.", | |
version="1.0.0" # 버전 정보 추가 | |
) | |
# Redis 클라이언트 연결 설정 (localhost 기준) | |
redis_client = redis.Redis(host='localhost', port=6379, db=0) | |
# 루트 엔드포인트: '/'로 접속했을 때 환영 메시지 출력 | |
@app.get("/") | |
def welcome(): | |
return { | |
"message": "🎉 환영합니다! Redis 기반 CRUD API에 오신 것을 환영합니다.", | |
"endpoints": { | |
"GET /items/{id}": "아이템 조회", | |
"POST /items/{id}?value=your_value": "아이템 생성", | |
"PUT /items/{id}?value=new_value": "아이템 수정", | |
"DELETE /items/{id}": "아이템 삭제", | |
"GET /version": "API 버전 정보" | |
} | |
} | |
# 버전 정보 엔드포인트 | |
@app.get("/version") | |
def get_version(): | |
return {"version": app.version} | |
# 아이템 조회 API (GET) | |
@app.get("/items/{id}") | |
def read_item(id: str): | |
value = redis_client.get(id) | |
if value: | |
return {"id": id, "value": value.decode()} | |
else: | |
return {"message": "Item not found"} | |
# 아이템 생성 API (POST) | |
@app.post("/items/{id}") | |
def create_item(id: str, value: str): | |
if redis_client.get(id): | |
return {"message": "Item already exists"} | |
else: | |
redis_client.set(id, value) | |
return {"id": id, "value": value} | |
# 아이템 수정 API (PUT) | |
@app.put("/items/{id}") | |
def update_item(id: str, value: str): | |
if redis_client.get(id): | |
redis_client.set(id, value) | |
return {"id": id, "value": value} | |
else: | |
return {"message": "Item not found"} | |
# 아이템 삭제 API (DELETE) | |
@app.delete("/items/{id}") | |
def delete_item(id: str): | |
if redis_client.get(id): | |
redis_client.delete(id) | |
return {"message": "Item deleted"} | |
else: | |
return {"message": "Item not found"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment