When building web applications, sending data from frontend to the server is a fundamental task. There are two common methods for passing parameters, i.e. path parameters and query parameters.
Each method has distinct use and choosing the right one can improve the clarity and functionality of our API. Let's explore the difference and see when to use each approach.
1. Path Parameters
Path parameters are included directly in the URL path, separated by forward slash. For example, to fetch specific category of products, the frontend sends request:
const BACKEND_URL = "https://api.example.com/products/";
const category = "electronics";
this.http.get(BACKEND_URL + category);
category
is the path parameter here. Backend route defined to capture this path parameter:
router.get("/:category", ProductsController.getAllProducts);
Use req.params.category
in the controller method to retrieve the category parameter:
const productCategory = req.params.category;
When to Use:
Path parameters are ideal when the parameter represents a resource identifier, like category name or a product ID.
For example, https://example.com/products/electronics
clearly identifies a category of products. This method creates clean and readable URLs.
2. Query Parameters
Query parameters are added to the URL after a question mark, separated by ampersand (if more than one). Query parameters can be passed as part of the query string:
const BACKEND_URL = "https://api.example.com/products/electronics";
// Using category as part of the backend url here, so that we can focus only on query parameters in this example
const queryParams = `?orderBy=price&direction=desc`;
this.http.get(BACKEND_URL + queryParams);
The backend route need no parameter since we are using query parameters:
router.get("", ProductsController.getAllProducts);
In the controller retrieve the parameter(s) from the query string:
const orderBy = req.query.orderBy;
const direction = req.query.direction;
When to Use:
Query parameters are suitable for searching, pagination or passing optional data. For example,
https://example.com/products/electronics?orderBy=price&direction=desc
appends additional options to sort the results. This method is more flexible, allowing multiple parameters without altering the URL structure but the url can get longer and difficult to read.
Choosing the Right Method
Path Parameters: Use when the parameter is essential to identify the resource.
Query Parameters: Use when the parameter is optional or for filtering, sorting, or pagination.
Note: I have written code examples in simple JavaScript to make it easier to understand.
Top comments (2)
Great explanation!
Thanks @oleh_nazarovych.