Skip to main content

Build Image Search App with Python and Flask

In our previous Python Flask tutorial, we have explained how to develop QR Code Generator with Python and Flask. In this tutorial, we will explain how to develop Image Search App with Python and Flask.

An image search is a search functionality that is implemented to find images. The search can be based on keywords, a picture, or a web link to an image.

Here in this tutorial, we will create an user friendly interface for searching images with keyword and implement functionality for image search using Unsplash API with Python and Flask.

So let’s proceed with developing Image Search App project:

1. Project Setup and Module Installation

First we will create our project image-search-python-flask directory .

$ mkdir image-search-python-flask

and moved to the project.

$ cd image-search-python-flask

Then we will install required modules for our application. As we will develop web based application, so we will install Flask micro framework module to create web application.

pip install Flask

2. Create Flask Application

We will create our project python file app.py and import required modules.

from flask import Flask, render_template, request, redirect, url_for
import sys
import os
import requests

Then we will create our Flask app and run app.

app = Flask(__name__)
app.secret_key = '1234567890'  

if __name__ == '__main__':
    app.run()

3. Create Image Search Form

Now we will create template file for our flask application. We will create templates directory in our project and create index.html template file. Then we will create search form to search image with keywords.

<div class="container">
  <div class="row">  
    <div class="col-md-6 mx-auto"><br>
	<h1>Image Search App Python</h1><br>
      <form method="POST" class="">
		{% if message %}
			<div class="alert alert-warning">{{ message }}</div>
		{% endif %}
		<div class="form-group">
			<label>Enter Keyword : </label><br />
			<input type="text" value="{{searchQuery}}" class="form-control" name="searchQuery" placeholder="enter keywords ...">
		</div>
		<br>
		<button type="submit" class="btn btn-primary">Search</button>       
      </form>
    </div>
  </div>
</div>

4. Implement Image Search with API

Then we implement function index() in app.py and implement functionality to search image with user inputted keyword. We will check for form submit and get keyword and then make unsplash API request with params to search images from API. Then finally return the search result with to template file to display search result.

@app.route('/', methods=['GET', 'POST'])
def index():    
    searchResult = ''
    message = ''
    searchQuery = ''
    clientId = 'y4i-BtdyHO0mBSE7BhqVPgCBFhqbaTtruS9oZmyKMho'
    if request.method == 'POST':        
        searchQuery = str(request.form['searchQuery'])
        if searchQuery:            
            apiUrl = 'https://api.unsplash.com/search/photos'
            params = {'query': searchQuery, 'client_id': clientId}
            response = requests.get(apiUrl, params=params, allow_redirects=True)
            searchResult = response.json()
        else:
            message = 'Please enter search keyword'
    return render_template('index.html', message = message, searchQuery = searchQuery,searchResult = searchResult)

5. Display Image Search Result

Finally, in index.html template file, we will display the search result.

<main>
  <section id="imgs" class="pt-5">
    <div class="container">
      <div class="row g-4" id="inputResults">    
        {% if searchResult %}
		  {% for image in searchResult.results %}
			  <div class="col-md-6 col-lg-4">
				<div class="card searchImg">
				<div id="cardImg">
				   <img
					src="{{image.urls.small}}"
					class="card-img-top"
					alt=""
					/></div>
				   <div class="card-body">
					<a
					  href=""
					  class="card-text"
					  target="_blank"
					  rel="noopener"
					  ></a
					>
				   </div>
				 </div>
			  </div>
		  {% endfor %}	
       {% endif %}     
	</div>          
   </div>
  </section>
</main>

Dwonlaod