How to Get Random Image from Unsplash, Pexels, and Pixabay

Sometimes, when designing a website or creating a project, you need a random image to fill a space. Fortunately, there are many free image APIs that you can use to get a random image. Three of the most popular ones are Unsplash, Pexels, and Pixabay.

In this tutorial, you will learn how to get a random image from Unsplash, Pexels, and Pixabay using Python and JavaScript.

Python Code

To get a random image from Unsplash, Pexels, and Pixabay using Python, you can use the requests and json modules. Here's an example code:

import requests
import json
import random

# List of API endpoints
endpoints = [
    '<https://api.unsplash.com/photos/random?client_id={YOUR_ACCESS_KEY}>',
    '<https://api.pexels.com/v1/photos/random>',
    '<https://pixabay.com/api/?key={YOUR_API_KEY}&q=&image_type=photo&orientation=horizontal>'
]

# Select a random API endpoint
endpoint = random.choice(endpoints)

# Send GET request to the selected endpoint
response = requests.get(endpoint)

# Parse JSON response
data = json.loads(response.text)

# Extract image URL from JSON data
if 'unsplash' in endpoint:
    image_url = data['urls']['regular']
elif 'pexels' in endpoint:
    image_url = data['src']['large']
else:
    image_url = data['hits'][0]['webformatURL']

# Print image URL
print(image_url)

Let's go through the code step by step:

  • We import the requests, json, and random modules.
  • We create a list of API endpoints for Unsplash, Pexels, and Pixabay.
  • We select a random API endpoint from the list.
  • We send a GET request to the selected API endpoint.
  • We parse the JSON response using the json.loads() method.
  • We extract the image URL from the JSON data based on the API endpoint.
  • We print the image URL.

Replace {YOUR_ACCESS_KEY} and {YOUR_API_KEY} with your actual access key or API key.

JavaScript Code

To get a random image from Unsplash, Pexels, and Pixabay using JavaScript, you can use the fetch API. Here's an example code:

const endpoints = [
    '<https://api.unsplash.com/photos/random?client_id={YOUR_ACCESS_KEY}>',
    '<https://api.pexels.com/v1/photos/random>',
    '<https://pixabay.com/api/?key={YOUR_API_KEY}&q=&image_type=photo&orientation=horizontal>'
];

const endpoint = endpoints[Math.floor(Math.random() * endpoints.length)];

fetch(endpoint, {
    headers: endpoint.includes('unsplash') ?
        { Authorization: 'Client-ID {YOUR_ACCESS_KEY}' } :
        { Authorization: '{YOUR_API_KEY}' }
})
    .then(response => response.json())
    .then(data => {
        let imageUrl;
        if (endpoint.includes('unsplash')) {
            imageUrl = data.urls.regular;
        } else if (endpoint.includes('pexels')) {
            imageUrl = data.src.large;
        } else {
            imageUrl = data.hits[0].webformatURL;
        }
        console.log(imageUrl);
    })
    .catch(error => console.error(error));

Let's go through the code step by step:

  • We create an array of API endpoints for Unsplash, Pexels, and Pixabay.
  • We select a random API endpoint from the array using Math.floor(Math.random() * endpoints.length).
  • We use the fetch() method to send a GET request to the selected API endpoint.
  • We set the headers option based on the API endpoint.
  • We parse the JSON response using the response.json() method.
  • We extract the image URL from the JSON data based on the API endpoint.
  • We log the image URL to the console.

Replace {YOUR_ACCESS_KEY} and {YOUR_API_KEY} with your actual access key or API key.

That's it! You now know how to get a random image from Unsplash, Pexels, and Pixabay using Python and JavaScript.

댓글 쓰기

0 댓글