API query parameters are key-value pairs that are appended to the URL of an API request to send additional information to the server. They allow clients (such as web browsers or applications) to specify certain criteria or pass data when making a request to the server.
Query parameters are added to the end of the URL after a question mark (?). Each parameter is a key-value pair, with the key and value separated by an equals sign (=). If there are multiple query parameters, they are separated by an ampersand (&).
How Query Parameters Are Used:
Filtering Data: Clients can use query parameters to filter the data they want. For example, ?category=books might tell the server to only return items from the "books" category.
Pagination: Query parameters are often used for pagination in API requests, allowing the client to specify which page of results to fetch and how many items per page. Example: ?page=2&limit=10.
Sorting and Ordering: Query parameters can be used to specify how data should be sorted. For example, ?sort=price&order=asc could instruct the server to return items sorted by price in ascending order.
Passing Search Terms: APIs often use query parameters to allow clients to search for data. For instance, ?search=laptop might be used to find all products that match the term "laptop."
Query parameters are highly flexible and can be used in various ways, depending on how the API is designed. They allow for dynamic interaction between the client and server, making it easier to request customized data.
// pages/api/greet.js export default function handler(req, res) { const { name } = req.query; // Get the 'name' query parameter const greeting = name ? `Hello, ${name}!` : 'Hello, stranger!'; res.status(200).json({ message: greeting }); }
Example usage:
/api/greet?name=John will return { "message": "Hello, John!" }
/api/greet will return { "message": "Hello, stranger!" }
// pages/api/user.js export default function handler(req, res) { const { name, age } = req.query; // Get 'name' and 'age' query parameters if (!name || !age) { res.status(400).json({ error: 'Name and age are required' }); return; } res.status(200).json({ message: `User ${name} is ${age} years old.` }); }
Example usage:
/api/user?name=Jane&age=28 will return { "message": "User Jane is 28 years old." }
/api/user?name=Jane will return { "error": "Name and age are required" }
// pages/api/score.js export default function handler(req, res) { const { player = 'Anonymous', score = '0' } = req.query; // Default values if missing res.status(200).json({ message: `${player} scored ${score} points!` }); }
Example usage:
/api/score?player=Alex&score=100 will return { "message": "Alex scored 100 points!" }
/api/score will return { "message": "Anonymous scored 0 points!" }
// pages/api/tags.js export default function handler(req, res) { const { tags } = req.query; // Get 'tags' query parameter (array) if (!tags) { res.status(400).json({ error: 'Tags are required' }); return; } res.status(200).json({ message: `You have selected these tags: ${tags.join(', ')}` }); }
Example usage:
/api/tags?tags=javascript&tags=react will return { "message": "You have selected these tags: javascript, react" }
/api/tags will return { "error": "Tags are required" }
// pages/api/items.js export default function handler(req, res) { const { page = 1, limit = 10 } = req.query; // Default values for page and limit const startIndex = (page - 1) * limit; const endIndex = startIndex Number(limit); // Dummy data for demonstration const items = Array.from({ length: 100 }, (_, i) => `Item ${i 1}`); const paginatedItems = items.slice(startIndex, endIndex); res.status(200).json({ currentPage: page, perPage: limit, items: paginatedItems, }); }
Example usage:
/api/items?page=2&limit=5 will return the next 5 items, such as { "items": ["Item 6", "Item 7", "Item 8", "Item 9", "Item 10"] }
/api/items (default values) will return the first 10 items, such as { "items": ["Item 1", "Item 2", ..., "Item 10"] }
These examples demonstrate the flexibility of using query parameters in Next.js API routes, covering common patterns like single or multiple parameters, optional values, arrays, and pagination.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3