python

requests 모듈로 JSON 다루기 (HTTP 요청)

베스트오버 2023. 5. 3. 23:08

1. GET 요청에서 JSON 데이터 가져오기

requests 모듈의 get 메서드를 사용하여 GET 요청을 보내고, 요청 결과로 받은 응답 데이터는 json 메서드를 이용하여 쉽게 JSON 형태로 파싱할 수 있습니다.

import requests

# GET 요청을 보내고
response = requests.get('https://jsonplaceholder.typicode.com/posts')

if response.status_code == 200:	
    data = response.json()	# 응답 데이터를 JSON으로 파싱
    print(data)
else:
    print('데이터 가져오기 실패')

 

2. POST 요청으로 JSON 데이터 보내기

requests 모듈의 post 메서드를 사용하여 POST 요청을 보내고, 보내는 데이터는 JSON 형태로 전송됩니다.

import requests

data = {'userId': '1', 'id': 1, 'title':'test_title', 'body':'test_body'}
headers = {'Content-Type': 'application/json'}

# POST 요청을 보내고
response = requests.post('https://jsonplaceholder.typicode.com/posts', json=data, headers=headers)

if response.status_code == 201:
    print('데이터 생성 성공')
else:
    print('데이터 생성 실패')

 

3. PUT 요청으로 JSON 데이터 업데이트

requests 모듈의 put 메서드를 사용하여 PUT 요청을 보내고, 보내는 데이터는 JSON 형태로 전송합니다.

import requests

data = {'userId': '10', 'id': 100, 'title':'test_title', 'body':'test_body'}
headers = {'Content-Type': 'application/json'}

response = requests.put('https://jsonplaceholder.typicode.com/posts/1', json=data, headers=headers)

if response.status_code == 200:
    print('데이터 업데이트 성공')
else:
    print('데이터 업데이트 실패')

 

4. DELETE 요청으로 JSON 데이터 삭제

requests 모듈의 delete 메서드를 사용하여 DELETE 요청을 보냅니다.

import requests

response = requests.delete('https://jsonplaceholder.typicode.com/posts/1')

if response.status_code == 200:
    print('데이터 삭제 성공')
else:
    print('데이터 삭제 실패')

 

5. JSON 데이터를 파일에 저장하기

requests 모듈을 사용하여 받은 JSON 데이터를 저장할 수도 있습니다. 이때, json 모듈을 사용하여 JSON 데이터를 문자열로 변환한 후 파일에 저장합니다.

import requests

response = requests.get('https://jsonplaceholder.typicode.com/posts')
json_data = response.json()

with open('data.json', 'w') as f:
    f.write(json.dumps(json_data))

 

6. 기타

# 바이너리 원문
response.content

# UTF-8로 인코딩된 문자열
response.text

# json() 함수를 통해 사전(dictionary)으로
response.json()

# 응답 헤더
response.headers

# 요청 쿼리 (params 사용)
response = requests.get("https://jsonplaceholder.typicode.com/posts", params={"userId": "1"})
[post["id"] for post in response.json()]	# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]