33 : Autocomplete in FastAPI

In the previous post, we implemented the search functionality in our web app. This search can be improved if our users get suggestions as they type in the search box. So, in this tutorial, we are going to implement this feature. We will be using Javascript and Jquery for this functionality and will also use a Jquery utility named Jquery UI. Currently, we have Bootstrap CDNs in the base.html file but bootstrap used a slip min version of Jquery which does not support '$' and ajax functionalities which we want to use so add the below additional CDNs in base.html file to support Jquery, and Jquery UI.

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    

<script src="{{ url_for('static', path='js/autocomplete.js') }}"></script>

The last line is not a CDN but our own static JS file that will help us in autocompletion. Let's see what we are doing in this  static > js > autocomplete.js file.

$( function() {
    $( "#autocomplete" ).autocomplete({
      source: "/jobs/autocomplete"
    });
  } );

We are basically telling Jquery UI to autocomplete to look for an input field that has an id attribute of #autocomplete. But our input field in the navbar is missing this id so, we need to modify templates > components > navbar.html and add this id attribute.

<input class="form-control me-2" name="query" id="autocomplete" type="search" placeholder="Search" aria-label="Search">


Whatever the user types in this input field a request is automatically created as 127.0.0.1:8000/?term=whatevertyped. Notice the "term" in the URL we get a dictionary in the GET request which has a key named "term". So, we can look for it, and then the logic is simple. We already have a seach_job function. We can utilize this search_job function to get jobs and create a list of suggestions.
For that put the following code in apis > version1 > route_jobs.py

from typing import Optional
from db.repository.jobs import search_job

#...


@router.get("/autocomplete")
def autocomplete(term: Optional[str] = None, db: Session = Depends(get_db)):
    jobs = search_job(term, db=db)
    job_titles = []
    for job in jobs:
        job_titles.append(job.title)
    return job_titles

Time to test our implementation, But before that keep your Javascript console ready, In case an error has crept in, It will show in the browser's console. Try to type some job title in the input field. If everything is fine, it should work.
 

Final git commit : https://github.com/nofoobar/JobBoard-Fastapi/commit/3b8ac12ff7777e9f4aea6baba92f976e3ab17c08

Prev: 32 : Search …