Create an amazing Image Search App using Pexels API

nehasoni__

Neha Soni

Posted on August 15, 2021

Create an amazing Image Search App using Pexels API

Hello Readers, Hope you all are doing well๐Ÿคฉ

In this blog post, you will learn how to build an amazing Image Search App using HTML, CSS, JavaScript, and API. So, let's get started โœŒ

Table of Content

- Setting up Pexels API
- Build an app
Enter fullscreen mode Exit fullscreen mode

Setting Up Pexels API

To set up Pexels API for your app, let's first create an account on pexels.

Step 1:- Open your favorite browser and navigate to pexels.com
Screenshot (427).png
Step 2:- After creating an account go to your profile logo on the right side and click on dropdown. Here, click on Image & Video API.
Screenshot (428).png

Step 3:- Click on Your API Key.
Screenshot (429).png
Step 4:- Now accept all terms, and give little information about your app to generate an API key.
Screenshot (430).png
After this step pexels will confirm your identity by sending an email to you. So confirm all the details.

Step 5:- After all the verification you will be redirected to your app and you will get your API key ๐Ÿ”‘.
Screenshot (431).png
Ok, now you have an API key so lets start coding our app.

Time to Code!!

Our Image Search App project contains three parts: HTML, CSS, and JavaScript. So first you need to create three files, the first one is HTML File(index.html), the second one is CSS file(style.css) and the third one is JS file(index.js).

HTML Part

Open your index.html file and type the following code inside it.

<!DOCTYPE html>
<html>
    <head>
        <!--META information-->
        <meta charset="UTF-8">
        <meta name="description" content="Image Search App">
        <meta name="keywords" content="HTML,CSS,JavaScript, images, API">
        <meta name="author" content="Neha Soni">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!--End of META information-->
        <title>Image Search App</title>
        <!--LINK CUSTOM CSS FILE-->
        <link rel="stylesheet" href="./style.css"> 
    </head>
    <body>
        <h1>Image Search Gallery </h1>
        <div class="container">
            <!--Input box to take input from User-->
            <input type="text" class="input" placeholder="Search for Images๐Ÿ”Ž"/>
            <button class="search_btn">Search</button>
            <!--Images to be displayed here-->
            <div class="display_images"></div>
            <!--Button to load more images-->
            <button class="showmore">Show More</button>
        </div>
        <!--LINK CUSTOM JS FILE-->
        <script src="./index.js"></script>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

JavaScript Part

Now here comes the main part of our image search app. In this file, we will fetch the data from the API. Since fetching the data from API is an asynchronous process so we will use the async function to fetch the data. If you don't know how to use async/await I recommend you to go through How To Use Async/Await in JavaScript(article by Catalin Pit )

Let's discuss everything step by step:-

Step 1:- Store all the selectors you are going to use throughout this app.

const apikey="563492ad6f917000010000019b983f3b62fe43daa92e746d4553dd35";
const input=document.querySelector("input");
const search_btn=document.querySelector(".search_btn");
const showmore_btn=document.querySelector(".showmore");

let page_num=1;
let search_text="";
let search=false;
Enter fullscreen mode Exit fullscreen mode

Step 2:- Add the event listener to the input textbox to store the value of the text you want to search.

input.addEventListener("input",(event)=>{
    event.preventDefault();
    search_text=event.target.value;
})
Enter fullscreen mode Exit fullscreen mode

Step 3:- Create a function CuratedPhotos() to display the default images when you load the page for the first time and we are going to pass the parameter page_num in the function.

async function CuratedPhotos(page_num){
//code to be executed
}
Enter fullscreen mode Exit fullscreen mode

Step 4:-

  • In this function, we are going to use the following endpoint. https://api.pexels.com/v1/curated This endpoint enables you to receive real-time photos curated by the Pexels team.
  • When we fetch the data from API by using the fetch() method it returns a promise, to handle this promise we use await keyword. Whenever the promise gets resolved we will save the data in the response variable.
  • After that, we will call our display_images() method to display the images on the page.
async function CuratedPhotos(page_num){
    // fetch the data from api
    const data=await fetch(`https://api.pexels.com/v1/curated?page=${page_num}`, 
    {
        method: "GET",
        headers: {
            Accept: "application/json",
            Authorization: apikey,     //use the apikey you have generated
        },
    });
    const response=await data.json();   //convert the response to json 
    console.log(response);

    display_images(response);   // call the display_images method to display the images on page
}
Enter fullscreen mode Exit fullscreen mode

Step 5:- Now let's create our display_images() method to display all the images we have fetched from API.

  • In this function, we will use forEach loop to iterate on each item of an array.
  • We will create a div element and in this div we define the image.
  • After that append this div in main display_images div.
function display_images(response){
    //use forEach loop to iterate on each item
    response.photos.forEach((image) => {
        const photo=document.createElement("div");
        photo.innerHTML=`<img src=${image.src.large}>
        <figcaption> Photo By: ${image.photographer}๐Ÿ“ธ</figcaption>`;
        document.querySelector(".display_images").appendChild(photo);
    });
}
Enter fullscreen mode Exit fullscreen mode

Step 6:- Let's add an event listener to our search button, to search the images according to user input.

  • Show the alert if the user doesn't input any text in a textbox.
  • cleargallery() method is used to clear the curated photos.
  • Call the SearchPhotos() function to search images related to input(we will work on this method in next step)
search_btn.addEventListener("click",()=>{
    if(input.value==="")
    {
        alert("Please enter the some text")
        return;
    }
    cleargallery();
    search=true;
    SearchPhotos(search_text,page_num);
})
Enter fullscreen mode Exit fullscreen mode

Step 7:- Now let's work on SearchPhotos() method according to the input text.

  • First create a method SearchPhotos() method with two parameters, one is query(topic on which you want to search images) and page_num.
  • In this method, we are going to use https://api.pexels.com/v1/search API. This endpoint enables you to search Pexels for any topic that you would like.
  • After fetching the data, we will call our display_images() method to display the images on the page.
async function SearchPhotos(query, page_num){
    const data=await fetch(`https://api.pexels.com/v1/search?query=${query}&page=${page_num}`, 
    {
        method: "GET",
        headers: {
            Accept: "application/json",
            Authorization: apikey,
        },
    });
    const response=await data.json();
    console.log(response);

    display_images(response);
}
Enter fullscreen mode Exit fullscreen mode

Step 8:- cleargallery() method:

  • Just remove all the images from main div and re-initialize page_num to 1.
function cleargallery(){
    document.querySelector(".display_images").innerHTML="";
    page_num=1;
}
Enter fullscreen mode Exit fullscreen mode

Okay, one more step to complete the app๐Ÿฅฑ.

Step 9:- Add event listener to show more button. The purpose of this button is that when you click on it more images get load on the page.

  • If we are not searching for any specific thing(the load more curated photos) we will increment the page_num by one.
  • Else, call the SearchPhotos() method.
showmore_btn.addEventListener("click", () => {
    if(!search){  
        page_num++;
        CuratedPhotos(page_num);
    }
    else{
        if(search_text.value==="")
        return;
        page_num++;
        SearchPhotos(search_text,page_num);
    }
})
Enter fullscreen mode Exit fullscreen mode

In last, call the CuratedPhotos() function to start function at exact reloading of the page.

CuratedPhotos(page_num);
Enter fullscreen mode Exit fullscreen mode

Complete javascript code

index.js

const apikey="563492ad6f917000010000019b983f3b62fe43daa92e746d4553dd35"; //use the apikey you have generated
const input=document.querySelector("input");
const search_btn=document.querySelector(".search_btn");
const showmore_btn=document.querySelector(".showmore");

let page_num=1;
let search_text="";
let search=false;

input.addEventListener("input",(event)=>{
    event.preventDefault();
    search_text=event.target.value;
})

search_btn.addEventListener("click",()=>{
    if(input.value==="")
    {
        alert("Please enter the some text")
        return;
    }
    cleargallery();
    search=true;
    SearchPhotos(search_text,page_num);
})

function cleargallery(){
    document.querySelector(".display_images").innerHTML="";
    page_num=1;
}

async function CuratedPhotos(page_num){
    // fetch the data from api
    const data=await fetch(`https://api.pexels.com/v1/curated?page=${page_num}`, 
    {
        method: "GET",
        headers: {
            Accept: "application/json",
            Authorization: apikey,         //use the apikey you have generated
        },
    });
    const response=await data.json();     //convert the response to json 
    console.log(response);

    display_images(response);            // call the display_images method to display the images on page
}

function display_images(response){
    //use forEach loop to iterate on each item
    response.photos.forEach((image) => {
        const photo=document.createElement("div");
        photo.innerHTML=`<img src=${image.src.large}>
        <figcaption> Photo By: ${image.photographer}๐Ÿ“ธ</figcaption>`;
        document.querySelector(".display_images").appendChild(photo);
    });
}

async function SearchPhotos(query, page_num){
    const data=await fetch(`https://api.pexels.com/v1/search?query=${query}&page=${page_num}`, 
    {
        method: "GET",
        headers: {
            Accept: "application/json",
            Authorization: apikey,
        },
    });
    const response=await data.json();
    console.log(response);

    display_images(response);
}

showmore_btn.addEventListener("click", () => {
    if(!search){  
        page_num++;
        CuratedPhotos(page_num);
    }
    else{
        if(search_text.value==="")
        return;
        page_num++;
        SearchPhotos(search_text,page_num);
    }
})

CuratedPhotos(page_num);
Enter fullscreen mode Exit fullscreen mode

Now, our app is working we need to beautify itโœจ. So lets add some CSS to style our app ๐ŸŽจ.

CSS Part

style.css

* 
{
    margin: 0;
    padding: 0;
    font-family: "Poppins", sans-serif;
}

h1{
    text-align: center;
    padding: 10px;
}
.container 
{
    border-radius: 5px;
    margin: 5px;
    padding: 15px;
    box-shadow: 0 10px 40px -10px rgb(0 64 128 / 10%);
    border: 1px solid #eee;

}
input 
{
    padding: 10px;
    border: 1px solid #ddd;
    background: #f9fafc;
    width: 40%;
    font-size: 25px;
    margin-left: 25%;

}
.display_images{
    width: 80%;
    margin: 100px auto;
    display: grid;
    grid-template-columns: repeat(auto-fit,minmax(300px,1fr));
    grid-gap:30px;
}
.display_images img 
{
    width: 90%;
    border-radius: 5px;
    height: 240px;
    cursor: pointer;
}
figcaption
{
    font-weight: bold;
    font-size: 15px;
}
button{
    background-color: #4CAF50;
    color: white;
    font-size: 1.5rem;
    padding: 10px;
    cursor: pointer;
}
.showmore{
    margin: 0 auto;
  display: block;
}
Enter fullscreen mode Exit fullscreen mode

congrats.gif
You have now finished working on our app๐Ÿ‘.

I have also deployed the app, Here goes the live demo ๐Ÿš€

I hope you learned to use Pexels API and created an image search app.

If you enjoyed learning and find it useful please do like and share so that, it reaches others as well ๐Ÿค

Thanks for reading ๐Ÿ˜ƒ

I would โค to connect with you at Twitter | LinkedIn | GitHub

Let me know in the comment section if you have any doubt or feedback.

๐Ÿ™Œ Support

Buy Me A Coffee

See you in my next Blog article, Take care!!

Happy Learning๐Ÿ˜ƒ๐Ÿ˜ƒ

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
nehasoni__
Neha Soni

Posted on August 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About