반응형
Python에서 REST API를 사용하는 방법은 매우 간단하며, 주로 Requests 라이브러리를 사용합니다. Requests는 HTTP 요청을 쉽게 보낼 수 있도록 도와주는 Python의 표준 라이브러리입니다. 아래는 REST API를 사용하는 기본적인 방법을 단계별로 설명한 예제입니다.
1. Requests 설치
먼저 Requests 라이브러리를 설치해야 합니다.
pip install requests
2. GET 요청 보내기
GET 요청은 서버에서 데이터를 가져오는 데 사용됩니다.
import requests
# URL 설정
url = "https://jsonplaceholder.typicode.com/posts"
# GET 요청
response = requests.get(url)
# 응답 확인
if response.status_code == 200: # HTTP 상태 코드가 200이면 성공
data = response.json() # JSON 응답을 Python 객체로 변환
print(data)
else:
print(f"Failed to retrieve data: {response.status_code}")
3. POST 요청 보내기
POST 요청은 서버에 데이터를 전송할 때 사용됩니다.
import requests
url = "https://jsonplaceholder.typicode.com/posts"
# 전송할 데이터 (JSON 형식)
payload = {
"title": "foo",
"body": "bar",
"userId": 1
}
# POST 요청
response = requests.post(url, json=payload)
# 응답 확인
if response.status_code == 201: # HTTP 상태 코드가 201이면 리소스가 성공적으로 생성됨
print("Data successfully posted!")
print(response.json())
else:
print(f"Failed to post data: {response.status_code}")
4. PUT 요청 보내기
PUT 요청은 기존 데이터를 업데이트할 때 사용됩니다.
url = "https://jsonplaceholder.typicode.com/posts/1"
# 업데이트할 데이터
payload = {
"id": 1,
"title": "updated title",
"body": "updated body",
"userId": 1
}
# PUT 요청
response = requests.put(url, json=payload)
if response.status_code == 200:
print("Data successfully updated!")
print(response.json())
else:
print(f"Failed to update data: {response.status_code}")
5. DELETE 요청 보내기
DELETE 요청은 데이터를 삭제할 때 사용됩니다.
url = "https://jsonplaceholder.typicode.com/posts/1"
# DELETE 요청
response = requests.delete(url)
if response.status_code == 200:
print("Data successfully deleted!")
else:
print(f"Failed to delete data: {response.status_code}")
6. 헤더와 인증 추가
API 사용 시, 헤더(Header)나 인증(Authentication)이 필요한 경우가 많습니다.
url = "https://api.example.com/secure-endpoint"
# 헤더와 토큰
headers = {
"Authorization": "Bearer your_access_token",
"Content-Type": "application/json"
}
# GET 요청
response = requests.get(url, headers=headers)
if response.status_code == 200:
print("Authorized request succeeded!")
print(response.json())
else:
print(f"Failed to authorize request: {response.status_code}")
7. 예외 처리 추가
네트워크 문제 또는 API 서버 문제로 인해 요청이 실패할 수 있으므로, 예외 처리도 중요합니다.
import requests
url = "https://jsonplaceholder.typicode.com/posts"
try:
response = requests.get(url, timeout=5) # 타임아웃 설정
response.raise_for_status() # HTTP 에러 발생 시 예외 처리
print(response.json())
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
참고 자료
위 단계를 따라 하면 REST API를 쉽게 사용할 수 있습니다.
반응형
'언어 > Python' 카테고리의 다른 글
[ Python ] REST API 사용시 디버깅을 위해 외부/직접 호출 구분해서 실행하기 (0) | 2025.02.03 |
---|---|
[ Python ] REST API 기능 제공하기 (0) | 2025.02.03 |
[ Python ] 상위 폴더에 있는 모듈 import 시 경로 설정하기 (0) | 2025.01.12 |
[ Python ] Pandas 기본 사용하기 (0) | 2025.01.12 |
[ Python ] 설치하기 (특정 버전) (0) | 2025.01.11 |