• Bootcamp (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • Restful

    BootcampBackend2020-12-17


    Create Routes for REST API endpoint

    Our REST API that we build will have following functions.

    Method    Endpoints         Notes
    -------   ----------        ------
    GET	      /product	        Get all products
    GET	      /product/:id	    Get single product
    POST	    /product	        Add product
    PUT	      /product/:id	    Update product
    DELETE	  /product/:id	    Delete product

    5 ways to make HTTP Requests in Node.js

    1. HTTP - the Standard Library

      const https = require('https')
      https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
      let data = '';

    // A chunk of data has been recieved. resp.on(‘data’, (chunk) => { data += chunk; });

    // The whole response has been received. Print out the result. resp.on(‘end’, () => { console.log(JSON.parse(data).explanation); });

    }).on(“error”, (err) => { console.log(“Error: ” + err.message); });

    - no extra dependencies
    - receive response data in chunks rather than just providing a callback function to be executed as soon as all of the data is received. 
    - You also need to parse the response data manually. 
    
    2. Request
    ------------
    ```javascript
    const request = require('request');
     
    request('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', 
     { json: true }, (err, res, body) => {
      if (err) { return console.log(err); }
      console.log(body.url);
      console.log(body.explanation);
    });
    1. Axios

      const axios = require('axios');

    axios.get(’https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY’) .then(response => { console.log(response.data.url); console.log(response.data.explanation); }) .catch(error => { console.log(error); });

    concurrent requests:
    ```javascript
    var axios = require('axios');
    axios.all([
      axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2017-08-03'),
      axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2017-08-02')
    ]).then(axios.spread((response1, response2) => {
      console.log(response1.data.url);
      console.log(response2.data.url);
    })).catch(error => {
      console.log(error);
    });
    1. SuperAgent

      const superagent = require('superagent');

    superagent.get(’https://api.nasa.gov/planetary/apod’) .query({ apikey: ‘DEMOKEY’, date: ‘2017-08-02’ }) .end((err, res) => { if (err) { return console.log(err); } console.log(res.body.url); console.log(res.body.explanation); });

    5. bluebird
    ------------