[파이썬] requests 요청 파라미터 전달하기

In many cases, when making HTTP requests, we need to send query parameters along with the request. These parameters provide additional information to the server and help in retrieving the desired data. In this blog post, we will explore how to send request parameters using the requests library in Python.

Installing Requests

Before we begin, let’s make sure we have the requests library installed. If not, we can install it using pip:

pip install requests

Sending Request Parameters

To send request parameters using the requests library, we can use the params parameter of the get() function. The params parameter takes a dictionary of key-value pairs where the key represents the parameter name and the value represents the parameter value.

Here’s an example:

import requests

# Define the base URL
base_url = 'https://api.example.com'

# Define the request parameters
params = {
    'param1': 'value1',
    'param2': 'value2'
}

# Send the request with parameters
response = requests.get(base_url, params=params)

# Print the response
print(response.json())

In this example, we define the base URL as https://api.example.com and create a dictionary params with two parameters - param1 and param2.

We then pass the params dictionary as the value of the params parameter in the get() function. This will append the parameters to the URL as query parameters.

Finally, we send the request using requests.get() and print the response as JSON.

Handling Response

After sending the request with parameters, we receive a response from the server. We can handle the response based on the HTTP status code and the data returned by the server.

Here’s an example of how to handle the response:

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

if response.status_code == 200:
    # Request was successful
    data = response.json()
    # Process the data further
else:
    # Request failed
    print(f'Request failed with status code: {response.status_code}')

In this example, we first check the status code of the response. If it is 200 (indicating a successful request), we extract the JSON data returned by the server using response.json().

If the request failed (status code other than 200), we simply print an error message with the status code.

Conclusion

In this blog post, we learned how to send request parameters using the requests library in Python. By providing parameters, we can customize our requests and retrieve the desired data from the server.

Remember to install the requests library (pip install requests) and explore the official documentation for more advanced usage and options. Happy coding!