python requests get params in url

Python Requests Get Params in URL

If you are working with APIs, you might need to send some parameters to the server in order to retrieve specific data. One way to do this is by using the GET method, which allows you to pass parameters through the URL. In Python, you can use the requests library to make HTTP requests, including GET requests with parameters.

Sending Parameters in a GET Request

Let's say you want to retrieve information about a specific product from an API. The API requires you to provide the product ID as a parameter in the URL. Here's how you can do it using requests.get:


import requests

product_id = 123
url = f"https://api.example.com/products/{product_id}"

response = requests.get(url)

print(response.json())

In this example, we first define the product ID and the API URL with a placeholder for the ID. We then pass the URL to requests.get and store the response in a variable. Finally, we print the JSON data returned by the API.

Passing Parameters as a Dictionary

When you need to pass multiple parameters, it can be more convenient to store them in a dictionary and pass them as the params argument to requests.get. Here's an example:


import requests

params = {"category": "books", "limit": 10}
url = "https://api.example.com/products"

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

print(response.json())

In this example, we define a dictionary with the parameters we want to pass and the corresponding values. We then pass the dictionary to requests.get as the params argument. The resulting URL will have the parameters appended as query strings, like this:

https://api.example.com/products?category=books&limit=10

Encoding Parameters

When you pass parameters in the URL, you might need to encode them properly to avoid issues with special characters or spaces. The requests library takes care of this automatically, but it's worth knowing how it works.

The default encoding used by requests.get is UTF-8, which supports most characters used in URLs. If you need to use a different encoding, you can specify it using the encoding parameter.

Here's an example:


import requests

params = {"query": "coffee shop"}
url = "https://api.example.com/search"

response = requests.get(url, params=params, encoding="ISO-8859-1")

print(response.json())

In this example, we pass a parameter with a space in it, which would normally cause issues in a URL. However, we specify the encoding as ISO-8859-1, which supports spaces and other special characters. The resulting URL will look like this:

https://api.example.com/search?query=coffee%20shop

Conclusion

In this article, we've looked at how to pass parameters in a GET request using the requests library in Python. We've seen how to pass parameters as part of the URL or as a dictionary, and how to encode them properly. With this knowledge, you should be able to work with APIs that require GET parameters and retrieve the data you need.