AI Hints
Home›Elasticsearch Tutorial›Scan, FastAPI and a Search Service
Elasticsearch · Lesson 95 of 120

A Search API with FastAPI

A web API for search.

⏱ 2 min read▶ Video at 1:29:13🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Trailhead's website shouldn't talk to Elasticsearch directly. A small API sits in between. It takes the search words, builds a safe query, and returns clean results.

  • Website
  • Small API
  • Elasticsearch

A search endpoint

The search endpoint takes q from the URL. It runs a multi match query, and returns just names and prices. TestClient calls the endpoint without starting a server. Run it. Clean JSON results for the word rain.

api.pypython
from elasticsearch import Elasticsearch

es = Elasticsearch("http://localhost:9200")
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/search")
def search(q: str, size: int = 3):
    resp = es.search(index="products", size=size, source=["name", "price"],
        query={"multi_match": {"query": q, "fields": ["name^2", "description"]}})
    return [h["_source"] for h in resp["hits"]["hits"]]

print(TestClient(app).get("/search", params={"q": "rain"}).json())
Output
[{'name': 'Storm Rain Jacket', 'price': 230.99}, {'name': 'Breeze Rain Jacket', 'price':
110.99}, {'name': 'Cloudburst Rain Jacket', 'price': 315.99}]
Also uses _load
catalog

API design

Only expose what the site needs. Limit size, so nobody asks for a million results. Put the user's words inside the query, never build JSON by hand. And in production, run it with uvicorn.

keyvalue
Returnonly what's needed
sizecap it
User inputinside the query dict
Serveuvicorn api:app

Summary

A small FastAPI service sits between your website and Elasticsearch, and returns clean results. Next, practise with a full search service.

Key takeaways
  • FastAPI
  • /search
  • TestClient
Next up: Practice: Python Search Service — filters and facets