Create a simple REST API with expressJS

Create a simple REST API with expressJS

cover.png The REST API

The Representation State Transfer(REST) interface provide a set of operations that can be invoked by a remote client over a network, using the HTTP protocol

1.NodeJS Check tha tyour node and npm installed

To check if you have Node.js installed, run this command in your terminal. node -v

To confirm that you have npm installed you can this command in your terminal npm -v

if the above is instaqlled than we can proceed to create first mini restful API

Now lets start by created our project directory, run this command in your terminal mkdir simpleapi

Then navigate to the created directory also by running this command cd simpleapi Iniate anew NPM project with this command npm init and provide all the details request for

We are going to use ExpressJs nodeJs framework to create our API, so run the code below in your terminal

npm install express --save
npm install body-parser -- save

body-parser Parses incoming request bodies

Now we need to create our API entry point aap.js, also our route file

lets create the content of our app.js to start our server

const express = require('express')
const bodyParser = require('body-parser')
const routes = require('./routes/routes.js')

app.use(bodyparser.jsion())
app.use(bodyParser.urlencoded({ extended: true }))
routes(app);
app.listen(3000, ()=> {
    console.log('app running op port 3000')
})

Here we deind the prt where our server should be running on, but just onemore thing to finally start our awesome API, yeah!! the contents of our routes.js

var appRouter = (app) => {
    app.get('/', (req, res) =>{
        res.status(200)
           .send('welcome to our restful API')
})
}
module.exports  = appRouter;

The above code tells our server that anytime is a GET request to the root of our application it should print welcome to our restful API

Now w can go ahead and run API by typing node app.js in the reminal, you should get something like this printed on your terminal app running on port 3000. Now type visit http://localhost:3000 and see it pront the welcome message