Here’s how you can use JavaScript to display random images from the Pexels API on an HTML page:
Sign up for a Pexels API Key:
Go to the Pexels API page, sign up, and obtain an API key.
Create HTML and JavaScript:
Use JavaScript to fetch random images from Pexels and display them on your HTML page.
Here’s a sample implementation:
Create a simple HTML file with a container for the images.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Images from Pexels</title>
</head>
<body>
<h1>Random Images from Pexels</h1>
<div id="image-container"></div>
<script src="script.js"></script>
</body>
</html>
Place this code in a file named script.js. Replace YOUR_API_KEY with your actual Pexels API key. The following fetch method uses 2nd parameter to configure the authentication and authorization. You can also explicitly use method:GET.
const API_KEY = 'YOUR_API_KEY ';
const IMAGE_CONTAINER = document.getElementById('image-container');
async function fetchRandomImages() {
try {
const response = await fetch('https://api.pexels.com/v1/curated?page=5&per_page=4', {
headers: {
Authorization: API_KEY
}
});
const data = await response.json();
displayImages(data.photos);
} catch (error) {
console.error('Error fetching images:', error);
}
}
function displayImages(photos) {
IMAGE_CONTAINER.innerHTML = ''; // Clear any previous images
photos.forEach(photo => {
const img = document.createElement('img');
img.src = photo.src.medium; // Use 'medium' size image
img.alt = photo.photographer;
img.style.margin = '10px';
img.style.borderRadius = '8px';
IMAGE_CONTAINER.appendChild(img);
});
}
// Fetch random images when the page loads
fetchRandomImages();
Explanation
- API Endpoint: This code fetches curated photos (/v1/curated) from Pexels, which can act as a random collection.
- Authorization: The Authorization header includes your API key to authenticate with Pexels.
- Display Logic: Each photo's medium size URL is used to create <img> elements, which are then appended to image-container.
This will display five random images from Pexels on your page each time you refresh it. Adjust per_page in the API URL to get more or fewer images if needed.
Pexel official API client libraries
Pexel provides official API client libraries. What are they used for and How?
Pexels provides official API client libraries to make it easier for developers to interact with their API in different programming languages. These libraries handle the authentication, request formation, and response parsing, so you can focus on integrating images or videos into your project without having to write all the lower-level code for API calls.
Pexels offers official API clients for:
- JavaScript
- Python
- PHP etc.
Each of these libraries simplifies common tasks like searching for images, retrieving curated photos, or getting specific video clips directly from Pexels.
How to Use Pexels API Client Libraries
1. JavaScript (Node.js)
Install the Pexels client library using npm:
npm install pexels
Import the library and initialize the client with your API key:
const { createClient } = require('pexels');
const client = createClient('YOUR_API_KEY');
Example: Fetch curated photos
client.photos.curated({ per_page: 10 }).then(photos => {
photos.photos.forEach(photo => console.log(photo.src.medium));
});
Benefits of Using Official API Client Libraries
- Easier Setup: No need to manually set headers, format URLs, or handle response parsing.
- Error Handling: Built-in error handling and response codes make it easier to manage API errors.
- Convenience Methods: Provides functions for common tasks, like fetching curated photos or searching with specific parameters.
- Consistent Updates: Official libraries are updated when the API changes, so they are more likely to stay compatible.
- Using these client libraries allows you to integrate Pexels content into your project quickly and efficiently. Just replace "YOUR_API_KEY" with your actual API key and experiment with the available methods to meet your project’s requirements.
No comments:
Post a Comment