I have successfully created a basic Express-based API to serve JSON data, but now I want to enhance its functionality. The JSON file follows this structure: (some sections are excluded)
[{
"ID": "1",
"NAME": "George Washington",
"PAGE": "http://en.wikipedia.org/wiki/George_Washington",
"DATE1": "30/04/1789",
"DATE2": "4/03/1797",
"PARTY": "Independent ",
"IMG": "GeorgeWashington.jpg",
"THUMB": "thmb_GeorgeWashington.jpg",
"HOMESTATE": "Virginia"
}
Below is a snippet from my index.js for handling Express routing:
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
var myData = require('./data.json');
app.get('/api', function(req, res){
res.json(myData);
});
app.get('/api/:id', function(req, res){
res.json(myData[req.params.id]);
});
While a call to /api returns the entire dataset and /api/1 fetches the first entry, I aim to create another route that allows users to access specific elements within the JSON. For instance, calling
https//<blah>/api/1/HOMESTATE
should return
"HOMESTATE": "Virginia"
Is it possible to achieve this using parameters or do I need to iterate through the JSON based on the provided ID? Any guidance with code examples would be highly appreciated.