API Routes for Dynamic Endpoints
Create an API route that accepts dynamic parameters to fetch or post data, using a file named [...param].js and accessing the parameters through the req.query object.
import express from 'express';
const router = express.Router();
// Dynamic GET endpoint to fetch data
router.get('/api/:param*', (req, res) => {
// Access dynamic parameters
const params = req.params.param.split('/');
// Handle the parameters as needed, for example, use them for database querying
// Process and send back the data
res.json({ data: 'Some data based on ' + params.join(', ') });
});
// Dynamic POST endpoint to post data
router.post('/api/:param*', (req, res) => {
// Access dynamic parameters
const params = req.params.param.split('/');
// Access posted data from request body
const data = req.body;
// Handle the parameters and data as needed
// Respond with a success message or the created resource
res.status(201).json({ message: 'Data created based on ' + params.join(', '), createdData: data });
});
export default router;
This code sets up an Express router with two dynamic API endpoints. The first is a GET request that splits the dynamic URL segments and could use them to fetch data from a database. The second is a POST request that does the same for the dynamic URL segments and also processes JSON data submitted in the request body, potentially for creating a new database record.