Python .get()

THE-Spellchecker's avatar
Published Sep 14, 2022Updated May 15, 2024

The .get() method sends a GET request to a web server and it returns a response object.

  • Learn to analyze and visualize data using Python and statistics.
    • Includes 8 Courses
    • With Certificate
    • Intermediate.
      13 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

import requests

requests.get("url", **kwargs)

**kwargs are any number of dictionary items (named arguments) that are passed in as parameters. Many different named parameters can be passed into a GET request. For example, they can be used to include cookies in the request, set proxies, set user-agents, or set a page timeout.

Example

The .get() method sends a request for data to a web server. The response object it returns contains various types of data such as the webpage text, status code, and the reason for that response.

import requests
response = requests.get("https://codecademy.com")
print(f"{response.status_code}: {response.reason}")
response = requests.get("https://codecademy.com/cat-pictures")
print(f"{response.status_code}: {response.reason}")

This will produce the following output:

200: OK
404: Not Found

Codebyte Example

The .get() method can also take in various parameters. These parameters allow a user to communicate additional information to the web server such as the content type that should be returned, and the user’s authentication.

Code
Output

All contributors

Learn Python on Codecademy

  • Learn to analyze and visualize data using Python and statistics.
    • Includes 8 Courses
    • With Certificate
    • Intermediate.
      13 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours