Creating a Basic Express API

Image by Fabio Grandis from Pixabay

Scenario

{
"name": "fireflysemantics",
"greeting": "Hello there Fireflysemantics, it's nice to meet you!"
}

Approach

Setup

mkdir api
cd api
npm init -y
git init
touch .gitignore
vi .gitignore
npm i express
{
"name": "api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}

Implementation

touch hello-api.js
//Import express
const express = require('express')
//Create the express app
const app = express()
//Set the port
const port = 3000
//Test a hello get request endpoint
app.get('/', (req, res) => {
res.send('Hello World, from express');
});
//Start the server listening on our port
app.listen(port, () => console.log(`Starting the server listening on port ${port}!`))
ole@mkt:~/Temp/api$ node hello-api.js 
Starting the server listening on port 3000!
Hello World, from express
npm i body-parser
//Add this statement to the top of hello-api.js
const bodyParser = require('body-parser');
//Add this below the port configuration
app.use(bodyParser.urlencoded({ extended: false }));
ole@mkt:~/Temp/api$ node hello-api.js
// Test getting the name
app.get("/api/hello/:name", function (req, res) {
res.send("Name; " + req.params.name);
});
http://localhost:3000/api/hello/fireflysemantics
Name: fireflysemantics
// Test the capitalized  nameapp.get("/api/hello/:name", function (req, res) {    let name = req.params.name
let capitalizedName =
name.charAt(0).toUpperCase() +
name.slice(1)
res.send("Name: " + capitalizedName);
});
http://localhost:3000/api/hello/fireflysemantics
Name: Fireflysemantics
// Test the greeting responseapp.get("/api/hello/:name", function (req, res) {
let name = req.params.name
let capitalizedName = name.charAt(0).toUpperCase() + name.slice(1)
res.json(
{
name: name,
greeting: `Hello there ${capitalizedName}, it's nice to meet you!`
})
})
http://localhost:3000/api/hello/fireflysemantics
{"name":"fireflysemantics","greeting":"Hello there Fireflysemantics, it's nice to meet you!"}

Related Concepts

Brought to You By

--

--

Founder of Firefly Semantics Corporation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store