Open In App

How to Pass Parameters in URL with Python

Last Updated : 16 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Passing parameters in a URL is a common way to send data between a client and a server in web applications. In Python, this is usually done using libraries like requests for making HTTP requests or urllib .

Let's understand how to pass parameters in a URL with this example.

Example:

Python
import urllib.parse
params = {'name': 'shakshi', 'age': 21}
url = 'https://example.com?' + urllib.parse.urlencode(params)  # Encoding
print(url)

Output
https://example.com?name=shakshi&age=21

Explanation:

  • This code creates a dictionary with name and age as parameters.
  • It then adds these parameters to the URL using urlencode() to create a complete URL with query strings.

Passing Parameters with requests

This requests library allows us to easily send HTTP requests with parameters. By passing parameters through the params argument, they are automatically added and encoded into the URL.

Example:

Python
import requests
# Base URL
url = 'https://example.com/search'
# pass parameter
params = {'q': 'python'}
# Sending GET request 
response = requests.get(url, params=params)
# Print url with parameter and response
print(response.url)  
print(response.text)  

Explanation:

  • This code sets a base URL and a parameter q .
  • It sends a GET request with the parameter using requests.get().
  • URL with the parameter and the server's response content are printed.

Manually Encoding Parameters with urllib

urllib module allows us to manually encode parameters into a URL. We can create a query string by encoding a dictionary and appending it to the base URL.

Python
import urllib.parse
# Base URL
url = 'https://example.com/search'
# pass parameter
params = {'q': 'python'}
# Encoding 
encoded_params = urllib.parse.urlencode(params)
# URL with parameter
final_url = f'{url}?{encoded_params}'
print(final_url)

Explanation:

  • This code defines a base URL and a parameter q .
  • It manually encode the parameter into a query string.
  • Encoded parameters are appended to the base URL.

Sending Parameters in a POST Request

In POST request, parameters are sent in the body instead of the URL. This is commonly used for submitting forms or sensitive data like login credentials.

Python
import requests
# Base URL
url = "https://example.com/api"
# Parameters
data = {
    'username': 'shakshi',
    'password': 'password'
}
# Sending POST request
response = requests.post(url, data=data)  # Sending
print(response.status_code)

Explanation:

  • This code defines the URL and parameters to send in the POST request body.
  • It sends the request with the parameters in the body.
  • Response status code is printed to show the result of the request.

Next Article
Article Tags :
Practice Tags :

Similar Reads