성장일기/파이썬

[python] API POST 호출 방법 정리 (헤더,데이터전송,파일전송)

지추월자 2023. 6. 26. 09:31
반응형

requests.post() 함수는 HTTP POST 요청을 보내는 데 사용됩니다. 이 함수를 사용하여 서버에 데이터를 전송하고, 응답을 받을 수 있습니다. 아래는 requests.post() 함수를 사용하는 방법에 대한 예시입니다.

1. 기본적인 방법

import requests

url = "https://example.com/api"
data = {"name": "John", "age": 30}
response = requests.post(url, data=data)

print(response.text)

위 코드는 https://example.com/api URL로 데이터를 전송하는 POST 요청을 보냅니다. data 매개변수에 전송할 데이터를 딕셔너리 형태로 지정합니다. 응답은 response 변수에 저장되며, response.text 속성을 사용하여 응답 본문을 출력합니다.

2. 헤더를 지정하는 방법

import requests

url = "https://example.com/api"
data = {"name": "John", "age": 30}
headers = {"Authorization": "token"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

위 코드는 https://example.com/api URL로 데이터를 전송하는 POST 요청을 보냅니다. headers 매개변수에 전송할 헤더를 딕셔너리 형태로 지정합니다. 응답은 response 변수에 저장되며, response.text 속성을 사용하여 응답 본문을 출력합니다.

3. JSON 데이터를 전송하는 POST 요청

import requests
import json

url = "https://example.com/api"
data = {"name": "John", "age": 30}
headers = {"Content-Type": "application/json"}
json_data = json.dumps(data)
response = requests.post(url, data=json_data, headers=headers)
#response = requests.post(url, data=json.dumps(data), headers=headers)

print(response.text)

위 코드는 https://example.com/api URL로 JSON 데이터를 전송하는 POST 요청을 보냅니다. headers 매개변수에 Content-Type을 application/json으로 지정하여 JSON 데이터를 전송합니다. data 매개변수에는 JSON 데이터를 문자열로 직렬화한 값을 전달합니다. 응답은 response 변수에 저장되며, response.text 속성을 사용하여 응답 본문을 출력합니다.

4. 파일을 전송하는 POST 요청

import requests

url = "https://example.com/api"
files = {"file": open("example.txt", "rb")}
response = requests.post(url, files=files)

print(response.text)

위 코드는 https://example.com/api URL로 파일을 전송하는 POST 요청을 보냅니다. files 매개변수에 전송할 파일을 딕셔너리 형태로 지정합니다. 파일은 open() 함수를 사용하여 바이너리 모드로 열어서 전달합니다. 응답은 response 변수에 저장되며, response.text 속성을 사용하여 응답 본문을 출력합니다.

위 예시들은 requests.post() 함수를 사용하는 방법에 대한 다양한 예시입니다. 이를 참고하여 필요한 방식으로 requests.post() 함수를 사용하시면 됩니다.

반응형