How to Use Path Parameters in REST API: Simple Guide
In a REST API,
path parameters are dynamic parts of the URL used to identify specific resources. They are defined in the URL path using placeholders like {id} and extracted by the server to process requests for that specific resource.Syntax
Path parameters are placeholders in the URL path enclosed in curly braces {}. They represent variable parts of the URL that the client sends to specify which resource to access.
For example, in the URL /users/{userId}, {userId} is a path parameter that will be replaced by an actual user ID like /users/123.
The server framework extracts this value to use it in processing the request.
plaintext
/resource/{parameterName}Example
This example shows a simple REST API endpoint that uses a path parameter to get a user by their ID.
python
from flask import Flask, jsonify, request app = Flask(__name__) # Sample data users = { "1": {"name": "Alice", "age": 30}, "2": {"name": "Bob", "age": 25} } @app.route('/users/<user_id>', methods=['GET']) def get_user(user_id): user = users.get(user_id) if user: return jsonify({"userId": user_id, "details": user}) else: return jsonify({"error": "User not found"}), 404 if __name__ == '__main__': app.run(debug=True)
Output
Running the server and visiting http://localhost:5000/users/1 returns:
{"userId": "1", "details": {"name": "Alice", "age": 30}}
Common Pitfalls
- Missing parameter in URL: Forgetting to include the path parameter in the route definition or URL will cause errors or 404 responses.
- Incorrect parameter name: The name in the URL placeholder must match the function parameter name exactly.
- Not validating parameter values: Always check if the parameter value exists or is valid to avoid server errors.
python
# Wrong: parameter name mismatch @app.route('/users/<id>') def get_user(user_id): pass # Right: matching names @app.route('/users/<user_id>') def get_user(user_id): pass
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Path Parameter | Dynamic part of URL to identify resource | /users/{userId} |
| Placeholder Syntax | Use curly braces in URL path | /items/{itemId}/details |
| Extraction | Server extracts parameter value from URL | user_id in /users/ |
| Validation | Check if parameter value exists and is valid | Return 404 if not found |
Key Takeaways
Path parameters are dynamic URL parts enclosed in curly braces to identify specific resources.
The server extracts path parameters by matching placeholder names with function arguments.
Always validate path parameter values to handle missing or invalid inputs gracefully.
Use consistent naming between URL placeholders and server code parameters to avoid errors.
Path parameters make REST APIs flexible by allowing clients to specify which resource to access.