Python 24일 코스 - Day 18: HTTP 요청

Day 18: HTTP 요청

requests 라이브러리 설치

pip install requests

GET 요청

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code)  # 200
print(response.headers["content-type"])

data = response.json()
print(data["title"])

HTTP 메서드

메서드용도requests 함수
GET데이터 조회requests.get()
POST데이터 생성requests.post()
PUT데이터 수정 (전체)requests.put()
PATCH데이터 수정 (부분)requests.patch()
DELETE데이터 삭제requests.delete()

POST 요청

new_post = {
    "title": "새 글",
    "body": "Python에서 HTTP 요청 보내기",
    "userId": 1
}

response = requests.post(
    "https://jsonplaceholder.typicode.com/posts",
    json=new_post
)
print(response.status_code)  # 201
print(response.json()["id"])

쿼리 파라미터와 헤더

# 쿼리 파라미터
params = {"userId": 1, "_limit": 5}
response = requests.get(
    "https://jsonplaceholder.typicode.com/posts",
    params=params
)

# 커스텀 헤더
headers = {
    "Authorization": "Bearer YOUR_TOKEN",
    "Content-Type": "application/json"
}
response = requests.get(url, headers=headers)

에러 처리

def fetch_data(url):
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()  # 4xx, 5xx 에러 시 예외 발생
        return response.json()
    except requests.exceptions.Timeout:
        print("요청 시간이 초과되었습니다")
    except requests.exceptions.HTTPError as e:
        print(f"HTTP 에러: {e}")
    except requests.exceptions.ConnectionError:
        print("서버에 연결할 수 없습니다")
    return None

오늘의 연습문제

  1. 공개 API에서 날씨 데이터를 가져와 출력하는 프로그램을 작성하세요.
  2. GitHub API로 특정 사용자의 저장소 목록을 가져오세요.
  3. 여러 URL에서 데이터를 순차적으로 가져와 하나로 합치는 함수를 만드세요.

이 글이 도움이 되었나요?