Beginning API Development with Node.js
eBook - ePub

Beginning API Development with Node.js

Build highly scalable, developer-friendly APIs for the modern web with JavaScript and Node.js

Anthony Nandaa

Condividi libro
  1. 100 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Beginning API Development with Node.js

Build highly scalable, developer-friendly APIs for the modern web with JavaScript and Node.js

Anthony Nandaa

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

Learn everything you need to get up and running with cutting-edge API development using JavaScript and Node.js; ideal for data-intensive real-time applications that run across multiple platforms.

Key Features

  • Build web APIs from start to finish using JavaScript across the development stack
  • Explore advanced concepts such as authentication with JWT, and running tests against your APIs
  • Implement over 20 practical activities and exercises across 9 topics to reinforce your learning

Book Description

Using the same framework to build both server and client-side applications saves you time and money. This book teaches you how you can use JavaScript and Node.js to build highly scalable APIs that work well with lightweight cross-platform client applications. It begins with the basics of Node.js in the context of backend development, and quickly leads you through the creation of an example client that pairs up with a fully authenticated API implementation. By the end of the book, you'll have the skills and exposure required to get hands-on with your own API development project.

What you will learn

  • Understand how Node.js works, its trends, and where it is being used now
  • Learn about application modularization and built-in Node.js modules
  • Use the npm third-party module registry to extend your application
  • Gain an understanding of asynchronous programming with Node.js
  • Develop scalable and high-performing APIs using hapi.js and Knex.js
  • Write unit tests for your APIs to ensure reliability and maintainability

Who this book is for

This book is ideal for developers who already understand JavaScript and are looking for a quick no-frills introduction to API development with Node.js. Though prior experience with other server-side technologies such as Python, PHP, ASP.NET, Ruby will help, it's not essential to have a background in backend development before getting started.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Beginning API Development with Node.js è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Beginning API Development with Node.js di Anthony Nandaa in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Informatik e Webservices & APIs. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781789534177
Edizione
1
Argomento
Informatik

Building the API - Part 1

This chapter is meant to introduce the students to API building using Node.js. We will start by building a basic HTTP server to gain an understanding of how Node.js works.
By the end of this chapter, you will be able to:
  • Implement a basic HTTP server using the Node.js built-in http module
  • Implement a basic Hapi.js setup for an API
  • Describe the basic HTTP verbs and how they differ from each other
  • Implement various routes for the API, making use of the different HTTP verbs
  • Implement logging the web application
  • Validating API requests

Building a Basic HTTP Server

Let's begin by looking at the basic building blocks of a Node.js web application. The built-in http module is the core of this. However, from the following example, you will also appreciate how basic this can be.
Save the following code in a file called simple-server.js:
const http = require('http');
const server = http.createServer((request, response) =>
{
console.log('request starting...');
// respond
response.write('hello world!');
response.end();
});
server.listen(5000);
console.log('Server running at http://127.0.0.1:5000');

Use the simple-server.js file for your reference at Code/Lesson-2.
Now, let's run the file:
node simple-server.js
When we go to the browser and visit the URL in the example, this is what we get:

Setting up Hapi.js

Hapi.js (HTTP API), is a rich framework for building applications and services, focusing on writing reusable application logic. There are a number of other frameworks; notable among them is Express.js. However, from the ground up, Hapi.js is optimized for API building, and we will see this shortly when building our application.

Exercise 1: Building a Basic Hapi.js Server

In this exercise, we're going to build a basic HTTP server like the one before, but now with Hapi.js. You will notice how most of the things are done for us under the hood with Hapi.js. However, Hapi.js is also built on top of the http module.
For the rest of the exercises, from the first exercise of Chapter 3, Building the API – Part 2, we will be building on top of each exercise as we progress. So, we might need to go back and modify previous files and so forth:
  1. In your Lesson-2 folder, create a subfolder called hello-hapi.

Use the exercise-b1 folder for your reference at Code/Lesson-2.
  1. On the Terminal, change directory to the root of the hello-hapi folder.
  2. Initialize it as a basic Node.js project and run the following command:
npm init -y
  1. Create a file, server.js.
  2. Install Hapi.js by executing the following command:
npm install hapi --save
  1. In the file, write the following code:
const Hapi = require('hapi');
// create a server with a host and port
const server = new Hapi.Server();
server.connection
({
host: 'localhost',
port: 8000,
});
// Start the server
server.start((err) =>
{
if (err) throw err;
console.log(`Server running at: ${server.info.uri}`);
});

Use the server.js file for your reference at Code/Lesson-2/exercise-b1.
Let us try to understand the code:
  • We first start by requiring the Hapi.js framework that we just included.

Recall our subtopic, The Module System, in Chapter 1, Introduction to Node.js? We looked at third-party modules—this is one of them.
  • We then create a server by initializing the Server class, hence a new Hapi.Server().
  • We then bind that server on a specific host (localhost) and port (8000).
  • After that, we create an example route, /. As you can see, for each route created, we have to specify three major things (as keys of an object passed to the server.route method):
    • method: This is the HTTP method for that route. We're going to look more deeply at the types of HTTP verbs in a later section. For our example, we're using GET. Basically, as the name suggests, this gets stuff/resources from the server.
    • path: This is the path on the server to the particular resource we are getting.
    • handler: This is a closure (anonymous function) that does the actual getting.

We're going to look at another extra key, called config, in our main project.
  • After this setup is done, we then start the server using the server.start method. This method accepts a closure (callback function) that is called once the server has started. In this function, we can check whether any errors occurred while starting the server.
  1. Run the server by going to the Terminal, and run the following command:
node server.js
  1. You should see this printed on the Terminal:
Server running at: http://localhost:8000
You should see something similar to this at http://localhost:8000:
Open another Terminal, change directory to the same project folder, and run the same command, node server.js. We'll get this error: Error: listen EADDRINUSE 127.0.0.1:8000.

The reason we get this error is because we can on...

Indice dei contenuti