RESTful API
In the previous chapter, we used HTTP module to serve a simple website. Here, we will make a simple API!
// index.js file
const http = require("http");
const { schools, terms, courses } = require("./data.js");
const PORT = 5000;
const server = http.createServer(routes);
function routes(request, response) {
if (request.url === "/") {
response.write("Welcome to Madooei's Resume at JHU API!");
} else if (request.url === "/api/schools") {
response.write(JSON.stringify(schools));
} else if (request.url === "/api/terms" ) {
response.write(JSON.stringify(terms));
} else if (request.url === "/api/courses" ) {
response.write(JSON.stringify(courses));
}
response.end();
}
server.listen(PORT);
console.log(`Server is listening on port ${PORT}`);
Here is data.js
schools = [
{
Name: "Whiting School of Engineering",
},
];
terms = [
{
Name: "Fall 2019",
},
{
Name: "Spring 2020",
},
{
Name: "Fall 2020",
},
{
Name: "Spring 2021",
},
{
Name: "Fall 2021",
}
];
courses = [
{
OfferingName: "EN.500.112",
Title: "Gateway Computing: JAVA",
Term: "Fall 2019",
},
{
OfferingName: "EN.601.226",
Title: "Data Structures",
Term: "Fall 2019",
},
{
OfferingName: "EN.601.226",
Title: "Data Structures",
Term: "Spring 2020",
},
{
OfferingName: "EN.601.421",
Title: "Object Oriented Software Engineering",
Term: "Spring 2020",
},
{
OfferingName: "EN.601.226",
Title: "Data Structures",
Term: "Fall 2020",
},
{
OfferingName: "EN.601.280",
Title: "Full-Stack JavaScript",
Term: "Fall 2020",
},
{
OfferingName: "EN.601.226",
Title: "Data Structures",
Term: "Spring 2021",
},
{
OfferingName: "EN.601.421",
Title: "Object Oriented Software Engineering",
Term: "Spring 2021",
},
{
OfferingName: "EN.601.226",
Title: "Data Structures",
Term: "Fall 2021",
},
{
OfferingName: "EN.601.280",
Title: "Full-Stack JavaScript",
Term: "Fall 2021",
},
];
module.exports = { schools, terms, courses }
Run the application and then head over to your browser and try the following endpoints:
- http://localhost:5000/
- http://localhost:5000/api/schools
- http://localhost:5000/api/terms
- http://localhost:5000/api/courses
Try these endpoints in the Postman, too (as HTTP Get requests). The example above showcases the essence of how API servers are built using NodeJS. We will explore this further in future modules.