Using Unsplash API for Image Fetching

Marickian
By -
0
Using Unsplash API for Image Fetching

Using Unsplash API for Image Fetching

When building applications that require images, the Unsplash API provides a powerful alternative to generating images with AI. Instead of creating images from scratch, you can leverage Unsplash’s vast library of high-quality photos based on specific search queries.

Getting Started with Unsplash API

To begin using the Unsplash API, you typically need to sign up for a developer account and obtain an API key. This key allows you to make requests to the Unsplash API and retrieve images based on search terms.

If you're following along in a project or tutorial, the API key might already be provided. In case of missing or exceeded requests, you can always sign up on Unsplash and generate your own API key by navigating to the Unsplash API documentation.

Install Axios for API Requests

In this example, we use Axios to make HTTP requests to the Unsplash API. If you haven’t installed it yet, open your terminal and run:

npm install axios

Once Axios is installed, you can start fetching images from Unsplash.

Setting Up the Environment

To avoid exposing sensitive information like your API key, store it in an environment file (e.g., `.env.local`). Your environment file should include the following:

UNSPLASH_API_KEY=your_api_key_here

Remember to restart your development server after adding environment variables to ensure they are loaded properly. You can use the following command:

npm run dev

Constructing the Unsplash API Request

To search for an image based on a query (such as a city), you need to construct a URL for the Unsplash API request. Here's the general structure:

https://api.unsplash.com/search/photos?client_id=YOUR_API_KEY&query=CITY_NAME

The query parameter (`CITY_NAME`) determines what kind of image you’ll get. For example, you might search for a city like "Paris" or "New York" to get related images.

Example Code for Fetching Images

Here's a sample JavaScript code to fetch an image from Unsplash using Axios:


const axios = require('axios');

// Function to fetch an image from Unsplash
async function fetchImage(city) {
    const apiKey = process.env.UNSPLASH_API_KEY;
    const url = `https://api.unsplash.com/search/photos?client_id=${apiKey}&query=${city}`;
    
    try {
        const response = await axios.get(url);
        const imageUrl = response?.data?.results?.[0]?.urls?.raw || '';
        return imageUrl;
    } catch (error) {
        console.error('Error fetching image:', error);
        return '';
    }
}

// Example usage
const city = 'Paris';
const imageUrl = await fetchImage(city);

if (imageUrl) {
    console.log("Image URL:", imageUrl);
} else {
    console.log("No image found for the city.");
}
        

This function constructs the API URL, sends the request to Unsplash, and retrieves the first result’s image URL. If successful, it returns the image URL; otherwise, it logs an error.

Displaying the Image in Your Application

Once you retrieve the image URL, you can display it in your application using an <img> tag or a framework component like Next.js’s <Image /> component. For instance, in Next.js:


import Image from 'next/image';

export default function CityImage({ city }) {
    const [imageUrl, setImageUrl] = useState('');

    useEffect(() => {
        async function fetchData() {
            const url = await fetchImage(city);
            setImageUrl(url);
        }
        fetchData();
    }, [city]);

    return (
        <div>
            {imageUrl ? <Image src={imageUrl} alt={city} width={600} height={400} /> : 'Loading image...'}
        </div>
    );
}
        

This component dynamically fetches the image for a specific city and displays it. The useEffect hook is used to fetch the image when the component loads or the city changes.

Handling Errors and Limits

Be mindful that the Unsplash API comes with rate limits (depending on your plan), so if you hit the limit, you'll need to either upgrade your account or wait for the reset period. Always handle errors gracefully, as shown in the example code, to avoid breaking your application if the API request fails.

Conclusion

The Unsplash API provides a great way to fetch high-quality images based on user-defined queries. It's an excellent alternative to AI-generated images, especially when you want real-life photography. With Axios and environment variables, you can easily integrate it into your application while keeping your API keys secure.

Post a Comment

0Comments

Post a Comment (0)