Using the Public API Docs of https://picsum.photos/

If you are looking for a way to access high-quality, royalty-free images for your projects, then https://picsum.photos/ is the perfect solution for you. The website offers a simple and easy-to-use public API that allows you to fetch random or specific images in different sizes and formats. In this blog, we will explore how you can use the public API of https://picsum.photos/ in JavaScript with code examples.

Random Image

To fetch a random image from https://picsum.photos/, you can use the following URL:

const url = 'https://picsum.photos/200/300';

This URL will return a random image of size 200x300 pixels. You can change the size of the image by modifying the parameters in the URL. For example, if you want a 500x500 pixel image, you can use the following URL:

const url = 'https://picsum.photos/500';

Specific Image

If you want to fetch a specific image from https://picsum.photos/, you can use the following URL:

const url = 'https://picsum.photos/id/{image_id}/{width}/{height}';

In this URL, you need to replace the {image_id} placeholder with the ID of the image you want to fetch. You can find the ID of an image by visiting the website and looking at its URL. For example, the ID of this image is 0:

const url = 'https://picsum.photos/id/0/200/300';

Response Handling

Now that you know how to fetch random and specific images from https://picsum.photos/, let's see how you can handle the response in JavaScript. You can use the fetch() function to fetch the image and then set it as the source of an HTML image element. Here's an example:

const img = document.createElement('img');
img.src = 'https://picsum.photos/200/300';

img.addEventListener('load', () => {
    // Image is loaded
    document.body.appendChild(img);
});

img.addEventListener('error', () => {
    // Error loading image
});

In this example, we create a new image element and set its source to a random image from https://picsum.photos/. We then add event listeners to the image element to handle the load and error events. When the load event is fired, we append the image element to the body of the document.

Conclusion

In this blog, we explored how you can use the public API of https://picsum.photos/ to fetch random and specific images in different sizes and formats. We also saw how you can handle the response in JavaScript and display the fetched image in your web page. With this knowledge, you can easily integrate https://picsum.photos/ into your projects and add high-quality images to your web pages.

Related APIs

Public APIs — A directory of free and public apis

Built by @mddanishyusuf