params in requests python

What are Params in Requests Python?

Params in Requests Python is a way to pass parameters or arguments with the URL in a GET request. It is a dictionary that contains keys and values that correspond to the query parameters of the URL.

Example Usage

Let's say I want to use the OpenWeatherMap API to get the current weather for a specific city. I would use the following code:


import requests

url = "https://api.openweathermap.org/data/2.5/weather"
params = {
    "q": "London,uk",
    "appid": "API_KEY"
}

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

In this example, I am using the requests.get() method to make a GET request to the OpenWeatherMap API. The url variable contains the API endpoint URL. The params variable contains a dictionary with two keys: q and appid.

The q key represents the city and country code that I want to get the weather for. The appid key represents my API key that I obtained from OpenWeatherMap.

Multiple Ways to Use Params

There are actually multiple ways to use the params argument in the requests.get() method:

  • Dictionary: As seen in the example above, you can pass a dictionary to the params argument.
  • List of Tuples: You can also pass a list of tuples to the params argument. Each tuple should contain two elements: the key and the value.
  • String: You can pass a string to the params argument if you want to manually create the query string. However, this is not recommended as it is prone to errors.

Conclusion

The params argument in the requests.get() method is a powerful tool that allows you to pass parameters or arguments with the URL in a GET request. By using this argument, you can make your requests more specific and get the data you need from an API more efficiently.