creating a rest APIs using node.js express quickly and easily- part 1


Before we start talking about how creating a rest apis using node.js express quickly and easily , We must first know some things what is rest API? and what is node js? and what is node express?.

what is rest AI ?


It is like a homing pigeon that transmits your messages from one place to another, or a waiter who transfers your order from your table to the kitchen and brings your order from the Chef to you.

Rest API  does the same idea it transferred your request from the website to the server on which the site's database is located , and then he brings the information you requested to you.



apis examples?




1- Weather Snippets.

 2- Google utilizes APIs to display relevant data from user search queries.
  • 3- Pay with PayPal.
  • 4- Travel Booking.
  • 5- Spotify, which enables you to search for different types of music.
  • 6- NASA has an open API chock-full of satellite imagery and constellation data for public.

  • what is node js?


We all know the JavaScript language is the language that performs the movements in the browser, but this language we could not program with it outside the browser until a programmer call Ryan Dahl starting in 2009  Merge Google's V8 with several built-in libraries and called it Node.js.

Now with node js we can write our code with JavaScript, but we can use it outside the browser.

what is node js express?



Express It is designed for building web applications and APIs ,it  is a back end web application framework for Nodejs, released as free and open-source software under the MIT License.

What is middleware in Node js?

creating a rest APIs using node.js express quickly and easily


Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

we use middleware is that it allows both systems to operate independently. If one system is down for maintenance, the other system continues to operate. The messages between the two simply queue up in the middleware system until the other side becomes available.

what is cors in node js express?

CORS is shorthand for Cross-Origin Resource Sharing. It is a mechanism to allow or restrict requested resources on a web server depend on where the HTTP request was initiated .and it used to secure a certain web server from access by other website or domain.

what is body parser in express?

body-parser extracts the entire body portion of an incoming request stream and exposes it on req. body .

This body-parser module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST request.

what is json?

JSON stands for JavaScript Object Notation, JSON is a lightweight format for storing and transporting data, JSON is often used when data is sent from a server to a web page, and easy to understand.

steps to creating a rest APIs using node.js express?

1- download node js:

go to here  and download the LTS version of node js according to your system.


2- Install Express:

Now install Express by typing: 

$ npm install express --save

To install Express temporarily and not add it to the dependencies list: 

$ npm install express --no-save


3-install body parser:

Installation of body-parser module: 

You can visit the link to Install body-parser module. You can install this package by using this command.

npm install body-parser

After installing body-parser you can check your body-parser version in command prompt using the command.

npm version body-parser

4-install cors:

Installation is done using the npm install command: 

$ npm install cors

Creating A Local Server With Node & Express:

Steps to creating a local server:-

1- Set your variables In this example, we set our variable to port 8000.

const port = 8000;

2- Utilize the .listen() method Set your variable named server, and pass the listen method with two arguments port and listening.

const server = app.listen(port, listening);

The port argument refers to the port variable we set above. The listening argument refers to a callback function we create.

The listening function:

 This function will run when we execute the listen method to let you know that the server is running and on which port by logging messages to the console.

function listening(){ console.log("server running"); console.log(running on localhost: {$port}); }

Another way you might see this same server code written is with an arrow function. Here is an example of the same code using an arrow function:

const

 server = app.listen(port, ()=>{console.log(`running on localhost: ${port}`)})


What's an arrow function?

Arrow functions are a shorter, more efficient way to write functions. In what takes a regular function three lines of code, arrow functions can be written with one.

Here's an example of a regular function and then we'll write it as an arrow function:

Regular Function:


function addition(number){ return 4 + number }


addition(4); `


Arrow Function:


var addition = number => 4 + number

addition(4);

As you can see, there are less need for parenthesis and return statements, allowing the syntax to be much more compact. Both are acceptable ways of writing functions, and best practice would be for you to be consistent in how you write your code. Even if you choose not to write your code with arrow functions, you should still be aware of how they are written.

Routes: GET Requests:

In this example below, app.get() is used to make a GET request, the first parameter is the particular URL -- in this case our project home page, and a callback function to execute. Inside the callback function a response is sent using .send(), and in this case the response is a string that says 'hello world'. The real life execution of this code would mean that whenever the project home URL is visited in the browser, there will be a GET request made to the server, and the response will be shown in the browser, so the words 'hello world' would appear on the screen.


var express = require('express');
var app = express();
 // respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world');
})

Request and Response Parameters:


The req parameter signifies the "request" from the client to the server. The res parameter signifies the "response" from the server to the client.


In this example below, app.get() is used to make a GET request, the first parameter is the particular URL -- in this case our project home page, and a callback function to execute. Inside the callback function a response is sent using .send(), and in this case the response is a string that says 'hello world'. The real life execution of this code would mean that whenever the project home URL is visited in the browser, there will be a GET request made to the server, and the response will be shown in the browser, so the words 'hello world' would appear on the screen.


var express = require('express');
var app = express();
 // respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world');
})


Request and Response Parameters The req parameter signifies the "request" from the client to the server. The res parameter signifies the "response" from the server to the client

More Powerful GET Requests

Hello world is all well and good, but suppose we wanted to make a GET request for some more useful data. GET requests can return all kinds of data, for example, imagine we wanted a JavaScript object to hold user data for us.

  • At the top of the demo code we just looked at, we could create an empty JavaScript object with the code const appData = {}. The variable appData now acts as the endpoint for all our app data. Later we will learn how to POST data to the app endpoint, but first let's add the line of code that will return our JavaScript object when the GET request is made.
var express = require('express')
var app = express()
// Create JS object
const appData = {}
// Respond with JS object when a GET request is made to the homepage
app.get('/all', function (req, res) {
  res.send(appData)
})


In this example, we created a new route named '/all', so that the route 'localhost:3000/all' will now trigger the GET request, which will return the JavaScript object as laid out in the server code above.

Routes: POST Requests

One way to collect and store user data so that you can access it later is through making an HTTP POST request. Analogous to the .get() Express method, there is also a .post() method to handle HTTP POST requests. An HTTP POST request sends data to the project's endpoint, where it is stored and can be accessed through a GET request, which we covered in the last lesson. Here is what a simple POST request could look like using the Express method .post():


// POST method route
app.post('/', function (req, res) {
  res.send('POST received')
})


Here is how you could setup a basic POST route in the server side code.

First, Create an array to hold data:

const data = []


Then, create post() with a url path and a callback function:


app.post('/addMovie', addMovie )


In the callback function, add the data received from request.body. This is the key piece of information we are interested in from that long stretch of data we saw previously that the request (req) argument returns.

function addMovie (req, res){
   console.log(req.body)
   data.push(req.body)
}

Comments