Now go to your profile and navigate to Image & Video API
And you will see this section:
Click on Your API Key, add the APP name, and fill in the reason why you want to use Pexels.
Once filled, generate the API Key and copy it to use in Python.
Now, install the Pexels library:
pip install pexels-api
We also need to install the dotenv library to add a .env file:
pip install python-dotenv
Once the dependencies are installed, create a file named .env:
PEXELS_KEY = YOUR_API_KEY
Replace YOUR_API_KEY with the copied API Key.
Now create a Python file with the following content:
from pexels_api import API
import os
from dotenv import load_dotenv
load_dotenv()
PEXELS_KEY = os.getenv("PEXELS_KEY")
api = API(PEXELS_KEY)
api.search('dogs', page=1, results_per_page=5)
photos = api.get_entries()
for photo in photos:
print('Photo url: ', photo.url)
In this example, we are searching for dog images, with 1 page and 5 results per page.
This is the result:
Reading Time:2minutes
Hello, today we are going to learn how to use the Pexels API to retrieve images directly using Python.
The first thing we need to do is obtain a free Pexels API key.
Now go to your profile and navigate to Image & Video API
And you will see this section:
Click on Your API Key, add the APP name, and fill in the reason why you want to use Pexels.
Once filled, generate the API Key and copy it to use in Python.
Now, install the Pexels library:
pip install pexels-api
We also need to install the dotenv library to add a .env file:
pip install python-dotenv
Once the dependencies are installed, create a file named .env:
PEXELS_KEY = YOUR_API_KEY
Replace YOUR_API_KEY with the copied API Key.
Now create a Python file with the following content:
from pexels_api import API
import os
from dotenv import load_dotenv
load_dotenv()
PEXELS_KEY = os.getenv("PEXELS_KEY")
api = API(PEXELS_KEY)
api.search('dogs', page=1, results_per_page=5)
photos = api.get_entries()
for photo in photos:
print('Photo url: ', photo.url)
In this example, we are searching for dog images, with 1 page and 5 results per page.