[SOLVED] Trying to make a search bar which auto search on typing letters ( Flask-python +api call)

Issue

This Content is from Stack Overflow. Question asked by Nick Glav

It’s my first time using an API and I’m trying to make my search bar give back results on every letter that is typed ( i succeed to search on words but not on letters yet)

so I made a function that calls the API and returns some data based on the word(symbol) you are going to search

def lookup(symbol):
    """Look up quote for symbol."""

    # Contact API
    try:
        api_key = os.environ.get("API_KEY")
        url = f"https://cloud.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token={api_key}"
        response = requests.get(url)
        response.raise_for_status()
    except requests.RequestException:
        return None

    # Parse response
    try:
        quote = response.json()
        return {
            "name": quote["companyName"],
            "price": float(quote["latestPrice"]),
            "symbol": quote["symbol"]
        }
    except (KeyError, TypeError, ValueError):
        return None

this is my simple form

    <form action="/search" method="GET">
  <input
    type="search"
    autofocus
    name="symbol"
    id="symbol"
    placeholder="Write a stock quote"
  />

Can anyone give me an idea on how to do it, typing a letter and not a word?
With javascript or directly on python



Solution

you’d need to do it with js since the form will wait for a submit event which submits the whole form and clears it.

so it all depends what you’re using for your request. I’d either pick axios or fetch API (keep in mind the latter one won’t work with older browsers and you have to do some boilerplate yourself. this is just a basic example)

async function fetchSearchResult(value) {
    const response = await fetch("/search", <your options including the value - see link at the end>)
    <continue other code executions>
}

const input = document.querySelector('input[type="search"]');

input.addEventListener("input", e => fetchSearchresult(e.target.value))

you might want to throttle the eventlistener callback though (only calling the function once every x ms) since every character your user types in could mean a lot of request.

using fetch API

Axios


This Question was asked in StackOverflow by Nick Glav and Answered by s.Bergmann It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?