Node.js 101 - Create a small API
Tags: javascript, node, beginners, tutorial
Published: 2021-03-13 14:23:28

---
title: Node.js 101 - Create a small API
published: true
description: 
tags: javascript, node, beginner, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4anecy5mdl4pho8w7519.jpg
series: Node.js 101
---

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.

<h2>HTML response</h2>
In the last course, I create a server and send text and some html over. Here another example of a HTML response
```js
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')
})
```
<h2>JSON response</h2>
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 }
```
- 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:
```js
const friends = [
    {id: 1, name: 'Mike Taylor', age: 42},
    {id: 2, name: 'John Lamkin', age: 44},
]
```
This array of object can be converted to JSON like that
```js
// 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}]
```
To send JSON to client browser we need to specified the format in header.
```js
res.writeHead(200, {'Content-type': 'text/json' })
res.end(json)
```
![JSON](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/08zot64vktrzzti9w9lz.png)
Here a full example of sending JSON when a user visit: /api/friends
```js
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')
})
```

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:
```js
const pathName = req.url // '/api/friends/1'
// Array deconstructing
const [, , entity, id] = pathName.split('/') // ['', 'api', 'friends', '1']
```

Now that we have all our info it is easy to send only id: 1
```js
const friend = friends.find((friend) => friend.id === Number(id)))
const json = JSON.stringify(friend)
res.end(json) // {id: 1, name: 'Mike Taylor', age: 42}
```
<h2>It seems to be difficult?</h2>
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. 

<h2>Conclusion</h2>
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: <a href="https://twitter.com/justericchapman?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Follow @justericchapman</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>