[Python] How to Send GET Requests with Requests: Basics and Parameter Settings

When retrieving data from the web, the GET request is the most frequently used method. By using Python’s requests library, you can intuitively write requests in a dictionary (dict) format, not just for accessing a URL but also for adding parameters such as search conditions.

Here, I will explain the basic access method and how to safely send parameters using the params argument.

目次

Executable Sample Code

The following code assumes a scenario of hitting a hotel availability search API. We use the test service httpbin.org, which returns the request content sent to it as JSON. This allows you to verify how parameters are actually attached to the URL.

import requests

def main():
    # ---------------------------------------------------------
    # 1. Basic GET Request
    # ---------------------------------------------------------
    print("=== 1. Basic GET Request ===")
    
    # Target URL (Here we use a test API that echoes back the request content)
    base_url = "https://httpbin.org/get"
    
    # Sending the request
    response = requests.get(base_url)
    
    # Checking the result (Status code and part of the response)
    if response.status_code == 200:
        print("Success!")
        # Display response body (string)
        print(f"Response Body (Start): {response.text[:100]}...")
    else:
        print(f"Failed with status: {response.status_code}")

    # ---------------------------------------------------------
    # 2. GET Request with Parameters (Recommended Method)
    # ---------------------------------------------------------
    print("\n=== 2. GET Request with Parameters ===")
    
    # Search conditions: Assuming a search for a non-smoking room for 2 people in Kyoto
    # No need to manually write "?location=kyoto&guests=2..." at the end of the URL
    search_params = {
        "location": "Kyoto",
        "check_in": "2025-10-01",
        "guests": 2,
        "is_smoking": False,
        "keyword": "Onsen & Open-air Bath"  # Spaces and special characters are also automatically encoded
    }
    
    # Just passing the dictionary to the params argument automatically generates query parameters
    response_with_params = requests.get(base_url, params=search_params)
    
    # Check the actually generated URL
    print(f"Generated URL: {response_with_params.url}")
    
    # Check arguments received by the server (httpbin returns parameters in the args field)
    data = response_with_params.json()
    print("\nServer received params:")
    for key, value in data['args'].items():
        print(f"  {key}: {value}")

if __name__ == "__main__":
    main()

Explanation: Benefits of Using the params Argument

Although it is possible to create parameters by concatenating strings like ?key=value&key2=value2 to the end of the URL, using the params argument of requests.get() has the following significant benefits.

1. Automation of URL Encoding

Even if your parameters contain Japanese characters or special symbols like & (as seen in “Onsen & Open-air Bath” in the code example), the library automatically converts them into the correct format (URL encoding) such as %E6%B8%A9%E6%B3%89....

2. Code Readability and Maintainability

Managing parameters as a Python dictionary is much easier than creating a huge URL string. It simplifies changing values and adding or removing parameters based on conditional logic.

3. Automatic Type Handling

Integers (int) and floating-point numbers (float) are also automatically converted to strings and sent.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次