Python ModulesRequests TutorialSending Data in Requests

Sending Data in Requests

When interacting with APIs or web services, you often need to send data in various formats. The Requests library provides an easy way to send form data, JSON data, and even upload files.


Sending Form Data

Form data is typically sent using a POST request and is encoded as application/x-www-form-urlencoded.

Example: Sending Form Data

import requests
 
url = "https://example.com/login"
data = {
    "username": "user123",
    "password": "mypassword"
}
 
response = requests.post(url, data=data)
 
print("Status Code:", response.status_code)
print("Response Text:", response.text)

Sending JSON Data

JSON data is sent using a POST request with the json parameter. The Requests library automatically sets the Content-Type to application/json.

Example: Sending JSON Data

url = "https://jsonplaceholder.typicode.com/posts"
data = {
    "title": "Learning Python Requests",
    "body": "This is a sample post.",
    "userId": 1
}
 
response = requests.post(url, json=data)
 
print("Status Code:", response.status_code)
print("Response JSON:", response.json())

Uploading Files

You can upload files using the files parameter, which accepts a dictionary where the key is the form field name, and the value is a tuple or file object.

Example: Uploading a File

url = "https://example.com/upload"
file_path = "example.txt"
 
with open(file_path, "rb") as file:
    files = {"file": file}
    response = requests.post(url, files=files)
 
print("Status Code:", response.status_code)
print("Response Text:", response.text)

Try It Yourself

Problem 1: Send Form Data

Send a login request to https://example.com/login with username "testuser" and password "mypassword". Print the response text.

Show Solution
import requests
 
url = "https://example.com/login"
data = {
    "username": "testuser",
    "password": "mypassword"
}
 
response = requests.post(url, data=data)
print("Response Text:", response.text)

Problem 2: Upload an Image

Write a script to upload an image file named sample.jpg to https://example.com/upload.

Show Solution
import requests
 
url = "https://example.com/upload"
file_path = "sample.jpg"
 
with open(file_path, "rb") as file:
    files = {"image": file}
    response = requests.post(url, files=files)
 
print("Status Code:", response.status_code)

Mastering how to send data using Requests is essential for working with APIs and web services. Practice sending form data, JSON data, and files to build versatile Python applications!