What is Bing Autosuggest ?

If your application sends queries to any of the Bing Search APIs, you can use the Bing Autosuggest API to improve your users’ search experience. The Bing Autosuggest API returns a list of suggested queries based on the partial query string in the search box. As characters are entered into the search box, you can display suggestions in a drop-down list.

Reference : Microsoft Document
Step 1 : Create Bing Autosuggest Cognitive Service.
Step 2 : Implement Bing Autosuggest Cognitive service in Python Application.

I am using Visual studio, you can use any IDE, Also i am going use Flask so to demo Autosuggest.

Create Web Flask Project in visual studio, it will create Flask project with all required libraries.

Visual studio start screen

Just hit f5 or run and it will be up and running.
Lets comment what we do not need, in context of our Demo.
Go to templates folder and open layout.html, and comment about and contact us page li tag, we will work on index screen, if required we will create new menus.

Layout.html

Now go to views.py, this file contains all the route and python server code.
Comment About and contact route.

view.py

Create one file in templates folder called “BingAutosuggest.html”, as we will use this to search and display text of response.
Code for BingAutosuggest.html

{% extends "layout.html" %}

{% block content %}

<div class="panel panel-default">
    <div class="panel-heading">{{ title }}.</div>
    <div id="autocomplete" class="autocomplete">
        <input oninput="AutoSuggestionCall(this)" class="autocomplete-input"
               placeholder="Search Wikipedia"
               aria-label="Search Wikipedia">
        <ul class="autocomplete-result-list list-group" id="autoSuggestResut">
        </ul>

    </div>
</div>
<script type="text/javascript" charset="utf-8">
    function AutoSuggestionCall(t) {
        var url = "/CallBingAutosuggestAPI";
        console.log(t.value);
        var data = { searchq: t.value };
        console.log(data)
        $.post(url, data, function (response) {
            data = JSON.parse(response)
            document.getElementById("autoSuggestResut").innerHTML = "";
            data.suggestionGroups[0].searchSuggestions.forEach(function (item) {
                console.log(item.displayText)
                const li = document.createElement('li');
                const p = document.createElement('p');
                li.className = "list-group-item"
                li.textContent = item.displayText
                p.textContent = item.url;
                li.appendChild(p)
                document.getElementById("autoSuggestResut").appendChild(li)
            });
        });
    }
</script>
{% endblock %}

Now, in index.html, i have added following button

home page

Following the code of index.html, if you need.

{% extends "layout.html" %}
{% block content %}
<br />

<div class="panel panel-default">
    <div class="panel-heading">Web search Cognitive Services.</div>
    <div class="panel-body">
        <a class="btn btn-primary" href="{{ url_for('LoadBingAutosuggestForm') }}">Bing Autosuggest.</a>
    </div>
</div>
{% endblock %}


On click of this button, there is one route i added in views.py to open by bingautosuggest.html

view.py is as below.

from datetime import datetime
from flask import render_template
from flask import request
from Cognitive_Service import app
import http.client, urllib.parse, json

subscriptionKey = 'e306854b04d04dc4b919c8967c4ea7d6'
host = 'api.cognitive.microsoft.com'
path = '/bing/v7.0/Suggestions'
mkt = 'en-US'
query = ''

@app.route('/')
@app.route('/home')
def home():
    """Renders the home page."""
    return render_template(
        'index.html',
        title='Home Page',
        year=datetime.now().year,
    )

@app.route('/LoadBingAutosuggestForm')
def LoadBingAutosuggestForm():
    """Renders the about page."""
    return render_template(
        'BingAutosuggest.html',
        title='Azure Bing Autosuggest'
    )

@app.route('/CallBingAutosuggestAPI', methods=['POST'])
def CallBingAutosuggestAPI():
    headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
    query = urllib.parse.quote(request.form['searchq'])
    params = '?mkt=' + mkt + '&q=' + query
    conn = http.client.HTTPSConnection(host)
    conn.request ("GET", path + params, None, headers)
    response = conn.getresponse ()
    return response.read()

So, When the application run, it will render, Home screen, which is our index.html.

Click on Bing AutoSuggest, it will redirect to “LoadBingAutosuggestForm” which is our another route in views.py, which will reneder our “BingAutosuggest.html” as below


Now oninput, there is one function called “AutoSuggestionCall” in javascript which calls “CallBingAutosuggestAPI” route in views.py.

This function then call Azure service to send the searched string and return suggestions and on success response, we are displaying it on list under UL tag.

Note : if you are using Free tier of azure Bing Autosuggest cognitive service, which stats one call per second, so make sure you type one word every second, multiple word wont work and will give error saying, subscription allow’s only one word per second.

Hope it helps,
Post any queries or question