Skip to content

13. HTTP JSON API SERVER

murat aka edited this page Feb 6, 2018 · 2 revisions

HTTP JSON API SERVER (Exercise 13 of 13)

Write an HTTP server that serves JSON data when it receives a GET request
to the path '/api/parsetime'. Expect the request to contain a query string
with a key 'iso' and an ISO-format time as the value.

For example:

/api/parsetime?iso=2013-08-10T12:10:15.474Z

The JSON response should contain only 'hour', 'minute' and 'second'
properties. For example:

 {  
   "hour": 14,  
   "minute": 23,  
   "second": 15  
 }  

Add second endpoint for the path '/api/unixtime' which accepts the same
query string but returns UNIX epoch time in milliseconds (the number of
milliseconds since 1 Jan 1970 00:00:00 UTC) under the property 'unixtime'.
For example:

 { "unixtime": 1376136615474 }  

Your server should listen on the port provided by the first argument to
your program.

─────────────────────────────────────────────────────────────────────────────

HINTS

The request object from an HTTP server has a url property that you will
need to use to "route" your requests for the two endpoints.

You can parse the URL and query string using the Node core 'url' module.
url.parse(request.url, true) will parse content of request.url and provide
you with an object with helpful properties.

For example, on the command prompt, type:

 $ node -pe "require('url').parse('/test?q=1', true)"  

Documentation on the url module can be found by pointing your browser
here:
file:///home/ubuntu/.nvm/versions/node/v6.11.2/lib/node_modules/learnyouno
de/node_apidoc/url.html

Your response should be in a JSON string format. Look at JSON.stringify()
for more information.

You should also be a good web citizen and set the Content-Type properly:

 res.writeHead(200, { 'Content-Type': 'application/json' })  

The JavaScript Date object can print dates in ISO format, e.g. new
Date().toISOString(). It can also parse this format if you pass the string
into the Date constructor. Date.getTime() will also come in handy.

─────────────────────────────────────────────────────────────────────────────

HTTP JSON API SERVER (Exercise 13 of 13)

//////////////////////////////////////////////
/*  function exercise 13  JSON API SERVER   */
//////////////////////////////////////////////

function httpAPI(){
    
    var http = require('http'); // load networking module
    var port = process.argv[2]; // get the port number from args

    var url = require('url'); // load url module
    var result = '';
    
    var server = http.createServer(function (inStream, outStream) {  
        // socket handling logic 
        var parsedUrl = url.parse(inStream.url, true); // divede url into parts.
        var iso = parsedUrl.query.iso; // iso time
        var format = parsedUrl.pathname; // convert into date format 
        var time = new Date(iso); // time object
        
        console.log(parsedUrl);
        
        if(format=="/api/parsetime"){ // iso format to date
            
            result = {
                                hour:   time.getHours(),  
                                minute: time.getMinutes(),  
                                second: time.getSeconds() 
            };
            
        }
        
        if(format=="/api/unixtime"){ // iso format to unix datetime 
                        
            result = {
                unixtime : time.getTime()             
            };
        
        }
        
        if(Object.keys(result).length>0){ // count objects
                     
            outStream.writeHead(200, { 'Content-Type': 'application/json' });
            outStream.end(JSON.stringify(result)); // write the json to output
            
        }else{
            
            outStream.writeHead(404);
            outStream.end();          
        }
    });  
    
    server.listen(port);     
   
}

    httpAPI();

Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?iso=2018-02-06T22:30:01.587Z',
  query: { iso: '2018-02-06T22:30:01.587Z' },
  pathname: '/api/parsetime',
  path: '/api/parsetime?iso=2018-02-06T22:30:01.587Z',
  href: '/api/parsetime?iso=2018-02-06T22:30:01.587Z' }

Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?iso=2018-02-06T22:30:01.587Z',
  query: { iso: '2018-02-06T22:30:01.587Z' },
  pathname: '/api/unixtime',
  path: '/api/unixtime?iso=2018-02-06T22:30:01.587Z',
  href: '/api/unixtime?iso=2018-02-06T22:30:01.587Z' }

Your submission results compared to the expected:

────────────────────────────────────────────────────────────────────────────────

  1. ACTUAL: "{"hour":22,"minute":30,"second":1}"

  2. EXPECTED: "{"hour":22,"minute":30,"second":1}"

  3. ACTUAL: "{"unixtime":1517956201587}"

  4. EXPECTED: "{"unixtime":1517956201587}"

  5. ACTUAL: ""

  6. EXPECTED: ""

────────────────────────────────────────────────────────────────────────────────

Submission results match expected

PASS Your solution to HTTP JSON API SERVER passed!

Here's the official solution in case you want to compare notes:

─────────────────────────────────────────────────────────────────────────────

    var http = require('http')
    var url = require('url')
    
    function parsetime (time) {
      return {
        hour: time.getHours(),
        minute: time.getMinutes(),
        second: time.getSeconds()
      }
    }
    
    function unixtime (time) {
      return { unixtime: time.getTime() }
    }
    
    var server = http.createServer(function (req, res) {
      var parsedUrl = url.parse(req.url, true)
      var time = new Date(parsedUrl.query.iso)
      var result
    
      if (/^\/api\/parsetime/.test(req.url)) {
        result = parsetime(time)
      } else if (/^\/api\/unixtime/.test(req.url)) {
        result = unixtime(time)
      }
    
      if (result) {
        res.writeHead(200, { 'Content-Type': 'application/json' })
        res.end(JSON.stringify(result))
      } else {
        res.writeHead(404)
        res.end()
      }
    })
    server.listen(Number(process.argv[2]))

───────────────────────────────────────────────────────────────────────────── You've finished all the challenges! Hooray!

─────────────────────────────────────────────────────────────────────────────

Clone this wiki locally