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

Compartir libro
  1. 100 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y 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

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Beginning API Development with Node.js un PDF/ePUB en línea?
Sí, puedes acceder a Beginning API Development with Node.js de Anthony Nandaa en formato PDF o ePUB, así como a otros libros populares de Informatik y Webservices & APIs. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781789534177
Edición
1
Categoría
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...

Índice