Creating a Basic Express API
Scenario
We need to create an express endpoint /api/hello/:name
. If :name
is fireflysemantics
it should return this JSON object:
{
"name": "fireflysemantics",
"greeting": "Hello there Fireflysemantics, it's nice to meet you!"
}
Note that the name must be capitalized in the greeting.
We will be using Linux command line tools to illustrate how they can be used, but everything can be done in a text editor like VS Code as well.
Approach
Setup
Create a project directory:
mkdir api
cd api
Initialize the project:
npm init -y
Initialize git:
git init
Ignore node_modules
when committing code:
touch .gitignore
vi .gitignore
Add node_modules
to .gitignore
with vi
.
Install express:
npm i express
After the install package.json
should look like this ( cat package.json
):
{
"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"
}
}
The dependencies
section shows us that express
is installed.
Implementation
Create the javascript file hello-api.js
:
touch hello-api.js
Make the following edits hello-api.js
so that it contains the following.
//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}!`))
Start the server:
ole@mkt:~/Temp/api$ node hello-api.js
Starting the server listening on port 3000!
Start your browser and visit http://localhost:3000/
. You should see:
Hello World, from express
Now lets create our greeting endpoint.
First we need to install some middle ware so that express can decode the body of our http
request:
npm i body-parser
Then import and configure the body-parser
:
//Add this statement to the top of hello-api.js
const bodyParser = require('body-parser');
Configure the body parser:
//Add this below the port configuration
app.use(bodyParser.urlencoded({ extended: false }));
After this is done, start the app again and make sure it works:
ole@mkt:~/Temp/api$ node hello-api.js
It should log the normal startup message.
Now lets test grabbing the url parameters :name
// Test getting the name
app.get("/api/hello/:name", function (req, res) {
res.send("Name; " + req.params.name);
});
Start the server and try this request:
http://localhost:3000/api/hello/fireflysemantics
The browser should show:
Name: fireflysemantics
Lets capitalize the name:
// 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);
});
Restart server and visit:
http://localhost:3000/api/hello/fireflysemantics
The browser should show:
Name: Fireflysemantics
Finally return the JSON
greeting object. Notice that we are using res.json
instead of res.send
:
// 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!`
})
})
Restart the server and test the request:
http://localhost:3000/api/hello/fireflysemantics
The browser should show:
{"name":"fireflysemantics","greeting":"Hello there Fireflysemantics, it's nice to meet you!"}
Here’s the full source: