# API 속도 제한 처리

Copilot Chat 는 API 속도 제한을 감지하고 재시도 논리를 구현하는 코드를 제안하여 처리할 수 있습니다.

API를 요청할 때는 특정 시간 프레임 내에서 수행할 수 있는 호출 수를 제한하는 속도 제한이 발생하는 것이 일반적입니다.
GitHub Copilot Chat 는 속도 제한 응답을 검색하고 지연 후 자동으로 요청을 다시 시도하는 코드를 제안하여 이러한 제한을 처리하는 데 도움이 될 수 있습니다.

## 예제 시나리오

다음 Python 코드는 외부 API에서 날씨 데이터를 가져옵니다. API에 속도 제한이 있는 경우 제한이 초과되면 요청이 실패할 수 있으며, 앱은 재시도 논리를 구현하여 이러한 응답을 정상적으로 처리하는 방법이 필요할 수 있습니다.

```python id=rate-limit-example
from flask import Flask, request
import requests

app = Flask(__name__)

WEATHER_API_URL = "https://api.example.com/weather"

@app.route('/get_weather', methods=['GET'])
def get_weather():
    city = request.args.get('city')
    # Simulate an API request to the external weather service
    response = requests.get(WEATHER_API_URL, params={"city": city})
    weather_data = response.json()

    return weather_data
```

## 예제 프롬프트

```copilot copy prompt ref=rate-limit-example
How can I handle API rate limits within get_weather().
```

## 응답 예제

> \[!NOTE] 다음 응답이 예제입니다. Copilot Chat 응답은 비결정적이므로 여기에 표시된 응답과 다른 응답을 얻을 수 있습니다.

Copilot 는 재시도 빈도를 제한하기 위해 지수 백오프를 사용하여 재시도 메커니즘을 구현하는 코드를 제안할 수 있습니다.

다음은 그 예입니다.

```python
import requests
from flask import Flask, request
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

app = Flask(__name__)

WEATHER_API_URL = "https://api.example.com/weather"

def requests_retry_session(
    retries=3,
    backoff_factor=0.3,
    status_forcelist=(500, 502, 504),
    session=None,
):
    session = session or requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    return session

@app.route('/get_weather', methods=['GET'])
def get_weather():
    city = request.args.get('city')
    try:
        response = requests_retry_session().get(WEATHER_API_URL, params={"city": city})
        response.raise_for_status()
        weather_data = response.json()
    except requests.exceptions.RequestException as e:
        return {"error": str(e)}, 500

    return weather_data
```

이 예제에서는 특정 상태 코드(500, Copilot502, 504)로 인해 실패할 경우 코드가 요청을 자동으로 다시 시도할 수 있도록 하는 재시도 세션 설정이 제안됩니다.
`backoff_factor`는 재시도 사이의 지연이 점차 증가하여 API의 속도 제한을 더 이상 초과하지 않도록 방지할 수 있습니다.

## 추가 읽기

* [GitHub Copilot 채팅에 대한 프롬프트 엔지니어링](/ko/copilot/concepts/prompting/prompt-engineering)
* [GitHub 부필로트 사용에 대한 모범 사례](/ko/copilot/get-started/best-practices)