Skip to content

👽️ How to consume an API with Python

To consume an API in a simple way with python we will use the library called requests.

🔧 Preparing the Environment

python3 -m venv .venv # (1)
source .venv/bin/activate # (2)
pip install requests # (3)
  1. Creating a virtualenv (⚠ Change python3 to your python PATH if necessary)
  2. Activate the virtualenv (MacOS and Linux)
  3. Install requests
poetry add requests # (1)
  1. Install requests with Poetry

⌨️ Code

In this example we are going to consume an API that will return random fun facts and print it on screen.

consume_api.py
import requests # (1)


try:
    response = requests.get('https://api.aakhilv.me/fun/facts') # (2)
    response.raise_for_status() # (3)
    fun_fact = response.json()[0] # (4)
    print(f'Fun Fact: {fun_fact}') # (5)
except HTTPError as error: # (6)
    print(f'[{error.response.status_code}] {error}') # (7)
  1. Importing the requests library
  2. Performing the get on endpoint /fun/facts in the API
  3. Checking if the request returned any error status_code, in case of error it will generate an exception of type HTTPError (Line 9 handle this)
  4. Convert response to json and get first element from the return list
  5. Print on screen the random fun fact
  6. If line 6 raise an HTTPError exception, here it will be handled
  7. Print status_code information and the error

🚀 Running the Application

python consume_api.py

🖼️ Output

text

Comments