0
0
Rest-apiHow-ToBeginner ยท 4 min read

How to Use Query Parameters in REST API: Simple Guide

In a REST API, query parameters are added to the URL after a question mark ? to send extra information to the server. They are written as key-value pairs separated by &, like ?key1=value1&key2=value2, and help customize the API response.
๐Ÿ“

Syntax

Query parameters are appended to the base URL of a REST API endpoint after a ?. Each parameter is a key-value pair joined by =. Multiple parameters are separated by &.

  • Base URL: The main API address.
  • ? Starts the query string.
  • key=value pairs: Specify parameters and their values.
  • & separates multiple parameters.
plaintext
https://api.example.com/items?category=books&sort=price_asc
๐Ÿ’ป

Example

This example shows a simple REST API using Node.js and Express that reads query parameters to filter items by category and sort them by price.

javascript
import express from 'express';
const app = express();

const items = [
  { id: 1, name: 'Book A', category: 'books', price: 10 },
  { id: 2, name: 'Pen', category: 'stationery', price: 2 },
  { id: 3, name: 'Book B', category: 'books', price: 15 }
];

app.get('/items', (req, res) => {
  let filteredItems = items;

  // Filter by category if query parameter exists
  if (req.query.category) {
    filteredItems = filteredItems.filter(item => item.category === req.query.category);
  }

  // Sort by price ascending if requested
  if (req.query.sort === 'price_asc') {
    filteredItems = filteredItems.sort((a, b) => a.price - b.price);
  }

  res.json(filteredItems);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
Server running on http://localhost:3000
โš ๏ธ

Common Pitfalls

Common mistakes when using query parameters include:

  • Forgetting to encode special characters in parameter values, which can break the URL.
  • Assuming parameters are always present without checking, causing errors.
  • Using incorrect parameter names that the API does not recognize.
  • Not handling multiple values properly when expected.

Always validate and sanitize query parameters on the server side.

javascript
/* Wrong way: Not checking if parameter exists */
app.get('/search', (req, res) => {
  // This may cause error if 'term' is undefined
  const termLength = req.query.term.length;
  res.send(`Search term length: ${termLength}`);
});

/* Right way: Check before use */
app.get('/search', (req, res) => {
  if (!req.query.term) {
    return res.status(400).send('Missing search term');
  }
  const termLength = req.query.term.length;
  res.send(`Search term length: ${termLength}`);
});
๐Ÿ“Š

Quick Reference

Tips for using query parameters effectively:

  • Always start query parameters with ? after the base URL.
  • Separate multiple parameters with &.
  • Use meaningful parameter names that clearly describe their purpose.
  • Encode special characters in parameter values (e.g., spaces become %20).
  • Validate parameters on the server to avoid errors or security issues.
โœ…

Key Takeaways

Query parameters are added to REST API URLs after a question mark as key-value pairs.
Use query parameters to filter, sort, or customize API responses.
Always validate and check query parameters on the server to avoid errors.
Encode special characters in query parameter values to keep URLs valid.
Separate multiple query parameters with an ampersand (&).