how to do a post request in python?
- User
how to do a post request in python?
Assistant
You can make POST requests in Python using several methods. Here are the most common approaches:
Using the requests library (recommended)
First install requests if you haven't already:
pip install requestsThen you can make POST requests like this:
import requests # Simple POST with form data response = requests.post('https://httpbin.org/post', data={'key': 'value', 'name': 'John'}) print(response.text) # POST with JSON data json_data = {'user': 'alice', 'age': 25} response = requests.post('https://httpbin.org/post', json=json_data) print(response.json()) # POST with headers headers = {'Authorization': 'Bearer token123'} response = requests.post('https://httpbin.org/post', json={'data': 'example'}, headers=headers) # POST with timeout and error handling try: response = requests.post('https://api.example.com/data', json={'key': 'value'}, timeout=5) response.raise_for_status() # Raises an HTTPError for bad responses print(response.json()) except requests.exceptions.RequestException as e: print(f"Error: {e}")Using urllib (built-in)
If you can't use external libraries:
import urllib.request import urllib.parse import json # POST with form data data = urllib.parse.urlencode({'key': 'value'}).encode() req = urllib.request.Request('https://httpbin.org/post', data=data) response = urllib.request.urlopen(req) print(response.read().decode()) # POST with JSON json_data = json.dumps({'user': 'alice'}).encode() req = urllib.request.Request('https://httpbin.org/post', data=json_data, headers={'Content-Type': 'application/json'}) response = urllib.request.urlopen(req) print(response.read().decode())The requests library is generally preferred because it's more intuitive and handles many details automatically (like encoding, sessions, and error handling).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.