DEV Community

Cover image for Node.js 101 - Create a small API
Eric The Coder
Eric The Coder

Posted on • Updated on

Node.js 101 - Create a small API

I strongly recommend learning javascript first. Here a series of post I did on Dev.to: https://dev.to/rickavmaniac/javascript-my-learning-journey-part-1-what-is-javascript-role-and-use-case-49a3

I am now ready to continue my Node.js learning journey :)

Click follow if you want to miss nothing. I will publish here on Dev.to what I learn everyday.

Without further ado here is a summary of my notes for my last day.

HTML response

In the last course, I create a server and send text and some html over. Here another example of a HTML response

const http = require('http')
const server = http.createServer((req, res) => {
const pathName = req.url

    if (pathName === '/friends') {
        res.writeHead(200, {'Content-type': 'text/html' })
        res.end('<h1>This is my friends page</h1>')
    } else {
        res.writeHead(404, {'Content-type': 'text/html' })
        res.end('<h1>Page not found</h1>')
    }
    // send a response to client
})

// start server listening for request
server.listen(5000, 'localhost', () => {
    console.log('Server is listening at localhost on port 5000')
})
Enter fullscreen mode Exit fullscreen mode

JSON response

Today I will make an example on how to make a small API that return JSON.

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. In our case the API will exchange JSON data.

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications.

If you are new to API and JSON I strongly recommend to google those words and learn more about them.

In short the API is the web server app exposing the JSON data.

The web server application have dedicated url that client can request to received data. For example

GET request to retrieve all friends JSON data
http://example.com/api/friends

GET request to retrieve only friends no 1 JSON data
http://example.com/api/friends/1

Here a example of JSON data:

{ "name":"John", "age":30, "car":null }
Enter fullscreen mode Exit fullscreen mode
  • JSON objects are surrounded by curly braces {}.

  • JSON objects are written in key/value pairs.

  • Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).

  • Keys and values are separated by a colon.

  • Each key/value pair is separated by a comma.

JSON data ca be create in code, read from file, read from database or read over a third party API

In this example we will create the JSON data directly in code.
It is really easy to do so, Since JSON is Javascript Object Notation.

In Js we can create an array of objects like this:

const friends = [
    {id: 1, name: 'Mike Taylor', age: 42},
    {id: 2, name: 'John Lamkin', age: 44},
]
Enter fullscreen mode Exit fullscreen mode

This array of object can be converted to JSON like that

// Convert JS object to JSON string
const json = JSON.stringify(friends)
console.log(json) // [{"id":1, "name":"Mike Taylor","age":42},{"id": 2, "name":"John Lamkin","age":44}]
Enter fullscreen mode Exit fullscreen mode

To send JSON to client browser we need to specified the format in header.

res.writeHead(200, {'Content-type': 'text/json' })
res.end(json)
Enter fullscreen mode Exit fullscreen mode

JSON
Here a full example of sending JSON when a user visit: /api/friends

const http = require('http')
const friends = [
    {id: 1, name: 'Mike Taylor', age: 42},
    {id: 2, name: 'John Lamkin', age: 44},
]
const json = JSON.stringify(friends)
const server = http.createServer((req, res) => {
    const pathName = req.url

    if (pathName === '/api/friends') {
        res.writeHead(200, {'Content-type': 'text/json' })
        res.end(json)
    } else {
        res.writeHead(404, {'Content-type': 'text/html' })
        res.end('<h1>Page not found</h1>')
    }
    // send a response to client
})

// start server listening for request
server.listen(5000, 'localhost', () => {
    console.log('Server is listening at localhost on port 5000')
})
Enter fullscreen mode Exit fullscreen mode

That code is good to retrieved all friends data but what about retrieving only a specific friend ex: api/friends/1

To do that we have to write code that split the url entity name and id. There are many way to accomplish that. Here is one way:

const pathName = req.url // '/api/friends/1'
// Array deconstructing
const [, , entity, id] = pathName.split('/') // ['', 'api', 'friends', '1']
Enter fullscreen mode Exit fullscreen mode

Now that we have all our info it is easy to send only id: 1

const friend = friends.find((friend) => friend.id === Number(id)))
const json = JSON.stringify(friend)
res.end(json) // {id: 1, name: 'Mike Taylor', age: 42}
Enter fullscreen mode Exit fullscreen mode

It seems to be difficult?

Dont worry you should never really code something like that. In Node.js there is a framework that manage to do that for you and it call Express.js

Express.js have a set of tools that automate all the complex stuff related to managing a server like routing, api and template. We only learn that to help us understand what append in the background. The goal here is only to understand the concept.

Conclusion

That's it for today. Tomorrow will put all that learning to good use and will make our first template. Stay tune!

Follow me on Twitter: Follow @justericchapman

Oldest comments (1)

Collapse
 
liyasthomas profile image
Liyas Thomas

This is cool. If you'd like to test your API endpoints, try Hoppscotch - API request builder for web : hoppscotch.io

GitHub logo hoppscotch / hoppscotch

👽 A free, fast and beautiful API request builder used by 150k+ developers. https://hoppscotch.io