Sending Parameters in URLs with the Python Requests Library

Feb 3, 2024 ยท 2 min read

When making API requests, you'll often need to send parameters along with the request URL to filter data, paginate results, or authenticate the request. The Python Requests library makes this easy by allowing you to pass a dictionary of parameters.

Here's an example GET request that passes two parameters, category and page:

import requests

url = 'https://api.example.com/products'

params = {
  'category': 'electronics',
  'page': 2
}

response = requests.get(url, params=params)

This will make a request to something like https://api.example.com/products?category=electronics&page=2.

The params dictionary gets formatted into URL parameters, handling things like escaping special characters and concatenating multiple parameters.

You can also pass a list of items as a parameter value to represent multiple values for the same key:

params = {
  'category': 'electronics', 
  'tags': ['on-sale', 'clearance']
}

This would produce a URL like:

https://api.example.com/products?category=electronics&tags=on-sale&tags=clearance

When passing sensitive information like API keys, you'll want to use the headers parameter instead of putting that information directly in the URL:

headers = {
  'Authorization': 'Bearer <api_key>' 
}

response = requests.get(url, headers=headers)

The Requests library handles all the intricacies of encoding and building request URLs for you. By passing parameters as a dictionary, you keep your code simple while still being able to generate complex requests.

Browse by tags:

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!