Skip to content
Rodja Trappe edited this page Aug 9, 2023 · 6 revisions

Introduction

In this a step-by-step tutorial, we'll learn how to create a "search as you type" cocktail lookup using NiceGUI. The website will allow users to type in the name of a cocktail, and as they type, it will display matching cocktails with their images. The full example can be fetched from the repository.

Prerequisites

  • Have Python 3.8 or greater installed.
  • Install NiceGUI with pip install nicegui.

Steps

1. Import Necessary Libraries

import asyncio
from typing import Optional
import httpx
from nicegui import events, ui

2. Setup the API Client

We'll be using httpx to make asynchronous HTTP requests to the cocktail database. Read more about why async is crucial in our FAQ.

api = httpx.AsyncClient()

3. Basic Search Function

Let's first create a simple version of the search function, without handling edge cases or optimizing the user experience.

async def search(e: events.ValueChangeEventArguments) -> None:
    '''Search for cocktails as you type.'''
    response = await api.get(f'https://www.thecocktaildb.com/api/json/v1/1/search.php?s={e.value}')
    results.clear()
    with results:  # enter the context of the the results row
        for drink in response.json()['drinks'] or []:  # iterate over the response data of the api
            with ui.image(drink['strDrinkThumb']).classes('w-64'):
                ui.label(drink['strDrink']).classes('absolute-bottom text-subtitle2 text-center')

4. Create the User Interface

The user interface is quite simple: a search field and a horizontal row which automatically breaks if there are too many results.

search_field = ui.input(on_change=search).props('outlined rounded).classes('w-96')
results = ui.row()

Note that the results row is cleared in the search function before adding new content.

Clone this wiki locally