아무거나/진짜 아무거나

Python에서 Github API "rate limit exceeded" 에러 해결 위해 API 요청 한도 늘리기

톰거봉 2022. 3. 1. 00:02

GitHub API는 unauthenticated user에 대해서는 API 요청을 시간당 60개까지만 허용한다. (IP로 검사함)

curl -I https://api.github.com/users/octocat/orgs

위의 커맨드를 통해서 아래와 같이 해당 타임 윈도우에 남은 요청 개수를 확인할 수 있다.

> x-ratelimit-remaining: 59

유저의 authentication 정보를 제공해주면, 이 한도를 시간당 5,000개까지 올릴 수 있다.

크롤링을 해야할 일이 생기면 5,000개 정도는 되어야 그래도 쓸만하다..

Default user-to-server rate limits for GitHub.com
User-to-server requests are limited to 5,000 requests per hour and per authenticated user. All requests from OAuth applications authorized by a user or a personal access token owned by the user, and requests authenticated with any of the user's authentication credentials, share the same quota of 5,000 requests per hour for that user.

인증을 하는 몇 가지 방법이 있는데 가장 간단한 방법은 GitHub의 personal access token을 이용하는 것이다.

GitHub 로그인 후 Settings > Developer Settings > Personal access tokens 메뉴에 들어가면

(또는 https://github.com/settings/tokens 접속)

Generate new token 버튼을 통해서 새 토큰을 발급받을 수 있다. 

이미 발급받아놓은 유효한 토큰이 있다면 그걸 사용해도 된다.

 

다음은 토큰을 발급받은 후 Python에서 Github API를 통해 json 데이터를 받아오는 예제이다.

import requests # pip install requests

res = requests.get("https://api.github.com/users/octocat",
    allow_redirects=True, auth=(<username>,<token>))
res.raise_for_status()
data = res.json()

print(data)

 

<username>에 GitHub 아이디, <token>에 발급받은 토큰을 입력하면 유저 인증을 할 수 있다.

파이썬 코드로 말고 shell에서 직접 데이터를 받아오고 싶다면 다음과 같이 사용하면 된다.

curl -I https://api.github.com/users/octocat -u <username>:<token>

끄읕

반응형