Search Implementation
Search is a specialized form of filtering that typically involves full-text search across multiple fields. Let's explore how to design search functionality in REST APIs.
Basic Search
Simple Query Parameter
GET /api/products?q=laptop
GET /api/products?search=wireless+mouse
GET /api/products?query=gaming+keyboard
Dedicated Search Endpoint
GET /api/products/search?q=laptop
POST /api/search
{
"query": "laptop",
"filters": { "category": "electronics" }
}
Search Features
Field-Specific Search
GET /api/products?title=laptop&description=gaming
GET /api/users?name=john&email=@gmail.com
Combined Search and Filter
GET /api/products?q=laptop&category=electronics&inStock=true
Search with Operators
GET /api/products?q=laptop+OR+notebook
GET /api/products?q="exact phrase"
GET /api/products?q=laptop+-refurbished # Exclude refurbished
Search Response Design
Include Relevance Score
{
"data": [
{
"id": "1",
"name": "Gaming Laptop",
"score": 0.95
},
{
"id": "2",
"name": "Laptop Stand",
"score": 0.72
}
],
"meta": {
"query": "laptop",
"total": 150,
"took": 45
}
}
Highlight Matches
{
"data": [
{
"id": "1",
"name": "Gaming Laptop",
"highlights": {
"name": "Gaming <em>Laptop</em>",
"description": "Powerful <em>laptop</em> for gaming..."
}
}
]
}
Exercise: Build a Search Function
Loading JavaScript Exercise...
Autocomplete/Suggestions
Endpoint Design
GET /api/products/suggest?q=lap
Response Format
{
"suggestions": [
{ "text": "laptop", "count": 150 },
{ "text": "laptop stand", "count": 23 },
{ "text": "laptop bag", "count": 18 }
]
}
Best Practices
1. Limit Result Size
GET /api/search?q=laptop&limit=20
2. Include Search Metadata
{
"meta": {
"query": "laptop",
"total": 1532,
"took": 45,
"maxScore": 0.98
}
}
3. Handle Empty Queries
// GET /api/products?q=
{
"error": {
"code": "EMPTY_QUERY",
"message": "Search query cannot be empty"
}
}
4. Document Search Syntax
## Search Syntax
- Simple: `?q=laptop`
- Phrase: `?q="gaming laptop"`
- Exclude: `?q=laptop -refurbished`
- Field: `?q=name:laptop`
Summary
| Feature | Example |
|---|---|
| Basic search | ?q=laptop |
| Field-specific | ?title=laptop |
| Combined | ?q=laptop&category=electronics |
| Suggestions | /suggest?q=lap |
Good search implementation considers performance, relevance ranking, and user experience.

