[python] FastAPI와 FourSquare API의 연동

FastAPI는 빠르고 현대적인 웹 프레임워크이며, FourSquare API는 장소 정보를 제공하는 RESTful API입니다. 이 블로그 포스트에서는 FastAPI를 사용하여 FourSquare API와 연동하는 방법에 대해 알아보겠습니다.

개발 환경 설정

먼저, FastAPI를 설치합니다.

pip install fastapi

그리고 FourSquare API를 사용하기 위해 개발자 계정을 생성하고 액세스 토큰을 발급받아야 합니다.

FastAPI 앱 생성

다음으로, FastAPI 앱을 생성합니다.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

FourSquare API와의 연동

FourSquare API와 연동하려면 requests 라이브러리를 사용하여 HTTP 요청을 보내야 합니다.

import requests

CLIENT_ID = 'your_client_id'
CLIENT_SECRET = 'your_client_secret'

def search_venues(query):
    url = 'https://api.foursquare.com/v2/venues/search'
    params = {
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'v': '20220101',
        'near': 'New York, NY',
        'query': query
    }
    response = requests.get(url, params=params)
    return response.json()

요청 처리

FastAPI 앱에서 FourSquare API를 호출하고 응답을 반환하는 핸들러를 작성합니다.

@app.get("/venues/{query}")
def get_venues(query: str):
    data = search_venues(query)
    return data

테스트

앱을 실행하고 /venues 엔드포인트에 요청을 보내서 FourSquare API로부터 장소 정보를 가져옵니다.

uvicorn main:app --reload

브라우저나 API 클라이언트를 통해 http://127.0.0.1:8000/venues/coffee와 같은 URL로 요청을 보냅니다.

결론

이제 FastAPI를 사용하여 FourSquare API를 연동하는 방법을 알게 되었습니다. FastAPI의 간결하고 직관적인 문법을 이용하여 다른 외부 API와의 연동도 쉽게 구현할 수 있습니다.

FastAPI 공식문서 FourSquare API 공식문서