Bootstrap FreeKB - Python (Scripting) - GET request
Python (Scripting) - GET request

Updated:   |  Python (Scripting) articles

The requests module can be used to issue a REST API request.

Here is how you can make a GET request.

#!/usr/bin/python
import requests

response = requests.get("http://www.example.com/api")
print(response)

 

You'll most likely want to use try / except / else to do something when some sort of exception is raised.

#!/usr/bin/python3
import requests

try:
  response = requests.get("http://www.example.com/api")
except requests.exceptions.Timeout:
  print(f"GET request timed out")
except requests.exceptions.RequestException as exception:
  print(f"Got the following exception: {exception}")
else:
  print(response)

 

HTTPBasicAuth can be used if a username and password are needed to connect to the API.

#!/usr/bin/python3
import requests
from requests.auth import HTTPBasicAuth

try:
  response = requests.get("http://www.example.com/api", auth = HTTPBasicAuth('john.doe','itsasecret'))
except requests.exceptions.Timeout:
  print(f"GET request timed out")
except requests.exceptions.RequestException as exception:
  print(f"Got the following exception: {exception}")
else:
  print(response)

 

Or like this, if you have an authorization token.

#!/usr/bin/python3
import requests

try:
  response = requests.get(
    "http://www.example.com/api", 
    headers={ "Authorization": "Token abc123" }
  )
except requests.exceptions.Timeout:
  print(f"GET request timed out")
except requests.exceptions.RequestException as exception:
  print(f"Got the following exception: {exception}")
else:
  print(response)

 

You may want to set the timeout (10 seconds in this example).

#!/usr/bin/python3
import requests

try:
  response = requests.get(
    "http://www.example.com/api", 
    headers={ "Authorization": "Token abc123" },
    timeout=10
  )
except requests.exceptions.Timeout:
  print(f"GET request timed out")
except requests.exceptions.RequestException as exception:
  print(f"Got the following exception: {exception}")
else:
  print(response)

 

Something like this could be returned. Notice this only returns just the response code, such as 200 OK.

<Response [200]>

 

Appending status_code to the response should return the return code, such as 200 (OK) or 404 (Not Found).

#!/usr/bin/python3
import requests
from requests.auth import HTTPBasicAuth

try:
  response = requests.get("http://www.example.com/api", auth = HTTPBasicAuth('john.doe','itsasecret'))
except requests.exceptions.Timeout:
  print(f"GET request timed out")
except requests.exceptions.RequestException as exception:
  print(f"Got the following exception: {exception}")
else:
  print(response.status_code)

 

Appending content to the response should return the raw body.

#!/usr/bin/python3
import requests
from requests.auth import HTTPBasicAuth

try:
  response = requests.get("http://www.example.com/api", auth = HTTPBasicAuth('john.doe','itsasecret'))
except requests.exceptions.Timeout:
  print(f"GET request timed out")
except requests.exceptions.RequestException as exception:
  print(f"Got the following exception: {exception}")
else:
  print(response.content)

 

Or text, to return the body as a string.

#!/usr/bin/python3
import requests
from requests.auth import HTTPBasicAuth

try:
  response = requests.get("http://www.example.com/api", auth = HTTPBasicAuth('john.doe','itsasecret'))
except requests.exceptions.Timeout:
  print(f"GET request timed out")
except requests.exceptions.RequestException as exception:
  print(f"Got the following exception: {exception}")
else:
  print(response.text)

 

Which should now return whatever text the API is returning.

Hello World

 

Almost always, JSON is returned.

#!/usr/bin/python
import requests

response = requests.get("http://www.example.com/api")
print(response.json())

 

Or you can store the JSON in a dictionary.

#!/usr/bin/python
import requests

response = requests.get("http://www.example.com/api")
dict = response.json()
print(dict)

 

If some issue occurs, you may want to set logging to DEBUG to view the full request and response, perhaps something like this.

#!/usr/bin/python3
import logging
from requests.auth import HTTPBasicAuth

try:
    import http.client as http_client
except ImportError:
    import httplib as http_client

http_client.HTTPConnection.debuglevel = 1

logFormatter = logging.Formatter(
        "[%(asctime)s %(levelname)s] %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
)

logger = logging.getLogger()

requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

fileHandler = logging.FileHandler("/path/log/my.log")
fileHandler.setFormatter(logFormatter)

consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)

logger.addHandler(fileHandler)
logger.addHandler(consoleHandler)
logger.setLevel(logging.INFO)

try:
  response = requests.get("http://www.example.com/api", auth = HTTPBasicAuth('john.doe','itsasecret'))
except requests.exceptions.RequestException as exception:
  print(f"Got the following exception: {exception}")
else:
  print(response.content)

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 61c5d0 in the box below so that we can be sure you are a human.