It is really simple creating an express API server.
All you have to do is basically requiring express, creating/importing the JSON data, setting up a route, setting up a listening port, and bam there is API access to your data.
Steps for creating an Express API server:#
Step 1: Importing Express, assigning it to app variable
1
2
| const express = require('express')
const app = express()
|
Step 2: Creating JSON data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| let persons = [
{
"id": 1,
"name": "Arto Hellas",
"number": "040-123456"
},
{
"id": 2,
"name": "Ada Lovelace",
"number": "39-44-5323523"
},
{
"id": 3,
"name": "Dan Abramov",
"number": "12-43-234345"
},
{
"id": 4,
"name": "Mary Poppendieck",
"number": "39-23-6423122"
}
]
|
Step 3: Setting up a route
1
2
3
| app.get('/api/persons', (request, response) => {
response.json(persons)
})
|
Step 4: Setting up a port:
1
2
3
4
5
| const PORT = 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
|