👩‍💻 Develope/Python

[Python] Requests

heywantodo 2024. 1. 29. 10:07
728x90
반응형

[Python] Requests

requests는 파이썬에서 HTTP 요청을 다루는 강력하고 사용자 친화적인 라이브러리다.

주로 웹 개발이나 API 통신과 관련된 프로젝트를 진행하는 경우 거의 필수적으로 사용된다.

간단하고 직관적인 API로 HTTP 요청을 처리하는 데 도움을 준다. 

 

request 모듈 설치

아래 명령어를 통해 간단하게 설치가 가능하다.

pip install requests

 

GET

request 모듈을 사용하여 간단한 GET 요청을 보내는 방법이다.

import requests

url = "https://api.example.com/data"
response = requests.get(url)

print(response.status_code)  # HTTP 상태 코드 출력
print(response.text)  # 응답 내용 출력

 

매개변수와 헤더 설정

GET 요청에 매개변수를 추가하거나 헤더 설정이 가능하다.

import requests

url = "https://api.example.com/search"
params = {'q': 'python', 'page': 1}
headers = {'User-Agent': 'MyApp/1.0'}

response = requests.get(url, params=params, headers=headers)

print(response.url)  # 실제 요청된 URL 출력
print(response.json())  # JSON 형태의 응답 처리

 

POST

POST 요청 또한 다음과 같은 코드로 보낼 수 있다.

import requests

url = "https://api.example.com/create"
data = {'name': 'John Doe', 'email': 'john@example.com'}

response = requests.post(url, data=data)

print(response.status_code)
print(response.json())

 

예외 처리

requests 모듈은 네트워크 오류 등 다양한 예외를 다루는 기능을 제공한다.

import requests

url = "https://api.example.com/data"

try:
    response = requests.get(url)
    response.raise_for_status()  # HTTP 에러를 감지하고 예외 발생
    print(response.text)
except requests.exceptions.HTTPError as errh:
    print(f"HTTP 에러 발생: {errh}")
except requests.exceptions.RequestException as err:
    print(f"에러 발생: {err}")
728x90
반응형