FastAPI에서 푸시 알람 기능 구현하기

FastAPI는 Python으로 웹 애플리케이션을 개발하는 데 사용되는 빠르고 간결한 프레임워크입니다. 이번 블로그 포스트에서는 FastAPI를 사용하여 푸시 알람 기능을 구현하는 방법을 알아보겠습니다.

1. 푸시 알람 서비스 선택

첫 번째로 해야 할 일은 푸시 알람 서비스를 선택하는 것입니다. 여러 푸시 알람 서비스 중 페이로드, 보안, 가용성, 가격 등을 고려하여 적합한 서비스를 선택해야 합니다.

여기서는 Firebase Cloud Messaging (FCM)를 사용하여 푸시 알람을 보내는 예시를 보여드리겠습니다.

2. FCM 설정

Firebase 콘솔에서 프로젝트를 생성하고 FCM을 활성화해야 합니다. 이를 위해 다음 단계를 따릅니다.

3. FastAPI 애플리케이션 설정

FastAPI 애플리케이션을 설정하기 위해 다음 패키지를 설치해야 합니다.

pip install fastapi firebase-admin pydantic uvicorn

다음으로, FCM 서버 키를 FastAPI 환경 변수로 설정해야 합니다.

from fastapi import FastAPI
import firebase_admin
from firebase_admin import credentials

app = FastAPI()

firebase_cred = credentials.Certificate("path/to/firebase/credentials.json")
firebase_admin.initialize_app(firebase_cred)

4. 푸시 알람 전송 엔드포인트 생성

이제 푸시 알람을 전송하기 위한 엔드포인트를 생성해보겠습니다.

from fastapi import FastAPI
from pydantic import BaseModel
from firebase_admin import messaging

app = FastAPI()

class PushNotification(BaseModel):
    title: str
    message: str
    token: str

@app.post("/send-push-notification")
async def send_push_notification(notification: PushNotification):
    message = messaging.Message(
        notification=messaging.Notification(
            title=notification.title,
            body=notification.message
        ),
        token=notification.token
    )
    response = messaging.send(message)
    return response

이제 /send-push-notification 엔드포인트로 POST 요청을 보내면, 알맞은 토큰과 함께 푸시 알람을 발송할 수 있습니다.

5. FastAPI 서버 실행

FastAPI 서버를 실행하기 위해 다음 명령어를 사용합니다.

uvicorn main:app --reload

6. 요약

이렇게 FastAPI와 Firebase Cloud Messaging을 사용하여 푸시 알람 서비스를 구현하는 방법을 알아보았습니다. FastAPI의 강력한 기능과 FCM의 편리한 인터페이스를 활용하여 다양한 알림 기능을 개발할 수 있습니다.

#FastAPI #푸시알람