This post is an introduction to build a simple WEB API
, we’ll only cover get request, (post, delete, put will be covered in an other post).
Express js is great for creating web application and web API.
We’re going to build and run our first web api application with express , Helloapi
application. if you don’t have node js already installed you can Install & run your first application Nodejs.
Install express
Create a helloexpress
directory to hold your application, and make that your working directory
$ mkdir helloexpress
$ cd helloexpress
create a file ‘app.js’
Now install Express in the Helloapi
directory and save it in the dependencies list. For example:
$ npm install express
Helloapi example
add the following code to app.js file, We use Visual studio code to edit the file:
var express = require('express');
var app = express();
var persons = [
{ id: '001', name :'malekbenz', mail:'[email protected]' },
{ id: '002', name :'user1', mail:'[email protected]' },
{ id: '003', name :'user2', mail:'[email protected]' },
{ id: '004', name :'user3', mail:'[email protected]' }
];
app.get('/', function (req, res) {
res.send('Welcome to express api');
});
app.get('/persons', function (req, res) {
res.json(persons);
});
app.listen(3000, function () {
console.log('App is listening on port 3000!');
});
Run the application
Run the application:
$ node app.js
The application starts a server and listens on port 3000 for connections. The app responds with “Welcome to express api” for requests to the root URL (/) or route.
load http://localhost:3000/persons in a browser to see the output.
The application is working