杰瑞科技汇

Python如何发送POST请求?

Of course! Making a POST request is a fundamental task in Python, especially for interacting with web APIs. The most popular and user-friendly library for this is requests.

Python如何发送POST请求?-图1
(图片来源网络,侵删)

Here’s a complete guide, from the basics to more advanced examples.

The requests Library (Recommended)

The requests library simplifies making HTTP requests. If you don't have it installed, open your terminal or command prompt and run:

pip install requests

Basic POST Request

The most common use case for a POST request is to send data to a server, usually in the form of JSON. This is how you typically interact with REST APIs.

Let's send a simple JSON payload to a test API endpoint.

Python如何发送POST请求?-图2
(图片来源网络,侵删)
import requests
import json # Used for pretty-printing the response
# The URL of the API endpoint
url = "https://httpbin.org/post"
# The data you want to send. This will be sent in the request body.
# For APIs, this is almost always a JSON object.
payload = {
    "name": "John Doe",
    "email": "john.doe@example.com",
    "age": 30
}
# Make the POST request
# The `json=` argument automatically sets the Content-Type header to 'application/json'
# and converts the Python dictionary to a JSON string.
response = requests.post(url, json=payload)
# --- Check the response ---
# 1. Check if the request was successful (status code 2xx)
if response.status_code == 200:
    print("Request successful!")
    # 2. Print the response content (the server's reply)
    # The response from httpbin.org/post includes the JSON data it received.
    print("\nFull JSON response from server:")
    print(json.dumps(response.json(), indent=4)) # .json() parses the JSON response
else:
    print(f"Error: Received status code {response.status_code}")
    print(response.text)

Explanation:

  • requests.post(url, ...): The function to make a POST request.
  • url: The target URL.
  • json=payload: This is the key part. It tells requests to:
    • Take the Python dictionary payload.
    • Serialize it into a JSON string.
    • Set the Content-Type header to application/json.
    • Put the JSON string in the body of the request.
  • response.status_code: The HTTP status code (e.g., 200 for OK, 404 for Not Found, 500 for Server Error).
  • response.json(): A convenient method that parses the JSON response from the server into a Python dictionary.

Sending Form Data

Sometimes, you need to send data as application/x-www-form-urlencoded, which is common for HTML forms. You can do this with the data= argument.

import requests
url = "https://httpbin.org/post"
# Data for a form (a dictionary of key-value pairs)
form_data = {
    'username': 'test_user',
    'password': 'a_very_secret_password',
    'remember_me': 'true'
}
# Use the `data=` argument for form data
response = requests.post(url, data=form_data)
if response.status_code == 200:
    print("Form data sent successfully!")
    print("\nServer received the data as:")
    # The 'form' key in the response shows the data as the server saw it
    print(response.json()['form'])
else:
    print(f"Error: {response.status_code}")

Adding Headers

Many APIs require you to send authentication tokens or other custom headers. You can do this with the headers= argument.

import requests
url = "https://api.example.com/data" # A hypothetical API URL
# The payload to send
payload = {
    "query": "get_user_data"
}
# Custom headers, including an API key for authentication
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY_HERE", # Replace with your actual key
    "Custom-Header": "some_value"
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
    print("Request with headers successful!")
    print(response.json())
else:
    print(f"Error: {response.status_code}")
    print(response.text) # API errors are often in plain text

Sending Files

You can also upload files using a POST request. The files argument handles this.

Python如何发送POST请求?-图3
(图片来源网络,侵删)
import requests
url = "https://httpbin.org/post"
# Open the file in binary read mode ('rb')
# The 'name' in the tuple is the name of the form field.
# The 'filename' is the name of the file on the server.
with open('my_document.pdf', 'rb') as f:
    files = {'file': (f.name, f)}
    response = requests.post(url, files=files)
if response.status_code == 200:
    print("File uploaded successfully!")
    # The server's response will contain details about the uploaded file
    print(response.json()['files'])
else:
    print(f"Error uploading file: {response.status_code}")

Handling Timeouts and Errors

Robust code should handle potential issues like network problems or slow servers.

import requests
from requests.exceptions import RequestException, Timeout, HTTPError
url = "https://httpbin.org/post"
payload = {"message": "test timeout"}
try:
    # Set a timeout of 5 seconds for both the connection and the read operation
    response = requests.post(url, json=payload, timeout=5)
    # If the request was successful, this line will be reached.
    # If the status code is an error (4xx or 5xx), raise_for_status() will raise an HTTPError.
    response.raise_for_status() 
    print("Success!")
    print(response.json())
except Timeout:
    print("Error: The request timed out.")
except HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
except RequestException as err:
    print(f"An error occurred during the request: {err}")

Summary of Key requests.post() Arguments

Argument Purpose Example
json= Sends data as JSON. Automatically sets Content-Type to application/json. requests.post(url, json={'key': 'value'})
data= Sends data as form-encoded (application/x-www-form-urlencoded). requests.post(url, data={'key': 'value'})
headers= Adds custom HTTP headers to the request. requests.post(url, headers={'Authorization': '...'})
files= Sends one or more files. requests.post(url, files={'file': ('name', open('file.txt', 'rb'))})
params= Adds query parameters to the URL (e.g., ?key=value). requests.post(url, params={'sort': 'asc'})
timeout= Sets a timeout for the request in seconds. requests.post(url, timeout=10)
分享:
扫描分享到社交APP
上一篇
下一篇