API Navigator Logo

Python Requests GET Example

Author: Newtum

This example shows how to make a simple HTTP GET request using the Python Requests library to retrieve data from a server or an API.

What is a GET Request?

An HTTP GET request is used to request data from a specified resource. It is one of the most common HTTP methods. GET requests should only retrieve data and should have no other effect.

Making a Basic GET Request

To make a GET request, simply call `requests.get()` with the URL of the resource you want to retrieve.

import requests

url = 'https://jsonplaceholder.typicode.com/posts/1'

response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    print('Success!')
    # Print the response content (as JSON)
    print(response.json())
else:
    print('Failed to retrieve data:', response.status_code)

Passing Parameters in the URL

You can add query parameters to your GET request by passing a dictionary to the `params` argument. Requests will correctly URL-encode them for you.

import requests

url = 'https://httpbin.org/get'
my_params = {'key1': 'value1', 'user_id': 123}

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

# The final URL will be https://httpbin.org/get?key1=value1&user_id=123
print('Final URL:', response.url)
print('Response JSON:', response.json()['args'])