Make Angular 13, MongoDB example with Node.js Express

The tutorial is an Angular 13 + MongoDB example with Node.js Express: CRUD. You can follow the introduction to create CRUD apps that use Angular 13 and Node js express rest API and MongoDB.

Following  the below steps to create Angular 13 + Node JS MongoDB crud application:

  • Step 1 – Create New Angular App
  • Step 2 – Create Components in Angular
  • Step 3 – Import Modules in app.module.ts
  • Step 4 – Create CRUD Routes
  • Step 5 – Build RESTful API using Node + Express js + MongoDB
  • Step 6 – Create Angular Service for REST API Consumption
  • Step 7 – Add code In app.component.html
  • Step 8 – Create Operation

Step 1 – Create New Angular App

First of all, open your terminal and execute the following command on it to install an Angular app:

Firstly, open your terminal and execute the  command to install an Angular app:

ng new my-new-app

Next, you need to execute the following command on the terminal to install angular material:

ng add @angular/material

Step 2 – Create Components in Angular

In this step, execute the following commands on the terminal to generate components in the angular application. Then, open your terminal and execute the below command:

ng g c components/add-book
ng g c components/book-detail
ng g c components/books-list

Step 3 – Import Modules in app.module.ts

In this step, visit the directory src/app and then open the file app.module.ts. After that you need to add the below code into the file:

...
...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [],
  imports: [
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: []
})
export class AppModule { }

Step 4 – Create CRUD Routes

In the step, you need to create routes with the help of Angular routes. You will make a consensus with components to enable the navigation in the CRUD application, then you need to add the following code in the app-routing.module.ts file.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BooksListComponent } from './components/books-list/books-list.component';
import { AddBookComponent } from './components/add-book/add-book.component';
import { BookDetailComponent } from './components/book-detail/book-detail.component';
const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'add-book' },
  { path: 'books-list', component: BooksListComponent },
  { path: 'add-book', component: AddBookComponent },
  { path: 'edit-book/:id', component: BookDetailComponent }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 5 – Build RESTful API using Node + Express js + MongoDB

In the step, we will introduce how to create RESTful API with Node and Express.js. We will learn to use MongoDB and how to handle data.

You need to execute the following command to invoke the REST API development with Node and Express.js:

mkdir node-rest-api && cd node-rest-api

Then you need to execute the command:

npm init -y

Next, you execute the below commands to install imperative npm packages that will help you to create REST APIs for your Angular CRUD system:

npm install express cors body-parser mongoose
npm install nodemon --save-dev

In order to store the data flawlessly, you can use a reliable database of what else could be a better choice than MongoDB. So, execute the command to create a node-backend/database directory, and generate the db.js file where all the logic will be piled up for invoking the MongoDB connection.

mkdir database && cd database && touch db.js

Next, you need to add the following code in node-backend/database/db.js file.

module.exports = {
    db: 'mongodb://localhost:27017/db'
};

Now, you have to create the Book model or schema, and create node-backend/model folder. Also, you need to create a Book.js file and add the below code into the file:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Book = new Schema({
  name: {
    type: String
  },
  price: {
    type: String
  },
  description: {
    type: String
  }
}, {
  collection: 'books'
})
module.exports = mongoose.model('Book', Book)

Then, you need to define the REST API routes using Express js in the node project. Then you can create node-backend/routes folder, and create book.routes.js file. You need to add the below code into it:

const express = require('express');
const app = express();
const bookRoute = express.Router();
let Book = require('../model/Book');
// Add Book
bookRoute.route('/add-book').post((req, res, next) => {
    Book.create(req.body, (error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
});
// Get all Book
bookRoute.route('/').get((req, res) => {
    Book.find((error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})
// Get Book
bookRoute.route('/read-book/:id').get((req, res) => {
    Book.findById(req.params.id, (error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})
// Update Book
bookRoute.route('/update-book/:id').put((req, res, next) => {
    Book.findByIdAndUpdate(req.params.id, {
    $set: req.body
  }, (error, data) => {
    if (error) {
      return next(error);
      console.log(error)
    } else {
      res.json(data)
      console.log('Book updated successfully!')
    }
  })
})
// Delete Book
bookRoute.route('/delete-book/:id').delete((req, res, next) => {
    Book.findByIdAndRemove(req.params.id, (error, data) => {
    if (error) {
      return next(error);
    } else {
      res.status(200).json({
        msg: data
      })
    }
  })
})
module.exports = bookRoute;

Now, sum up all the code and conjugate it in one place so that you can run your backend and propel the CRUD app development forward.

Next, you create and add the following code in the index.js file:

let express = require('express'),
  path = require('path'),
  mongoose = require('mongoose'),
  cors = require('cors'),
  bodyParser = require('body-parser'),
  mongoDb = require('./database/db');
mongoose.Promise = global.Promise;
mongoose.connect(mongoDb.db, {
  useNewUrlParser: true,
  useFindAndModify: false,
  useUnifiedTopology: true
}).then(() => {
    console.log('Database sucessfully connected ')
  },
  error => {
    console.log('Database error: ' + error)
  }
)
const bookRoute = require('./routes/book.routes')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(cors());
// Static directory path
app.use(express.static(path.join(__dirname, 'dist/angular-mean-crud-tutorial')));
// API root
app.use('/api', bookRoute)
// PORT
const port = process.env.PORT || 8000;
app.listen(port, () => {
  console.log('Listening on port ' + port)
})
// 404 Handler
app.use((req, res, next) => {
  next(createError(404));
});
// Base Route
app.get('/', (req, res) => {
  res.send('invaild endpoint');
});
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/angular-mean-crud-tutorial/index.html'));
});
// error handler
app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

Step 6 – Create Angular Service for REST API Consumption

In the step, you need to visit app/service directory in Angular project and create Book.ts class within.

Then, you add the following code in app/service/Book.ts file:

export class Book {
    _id!: String;
    name!: String;
    price!: String;
    description!: String;
}

Then, you need to execute the command to create a crud service file:

ng g s service/crud

Then, you need to add the below code in app/service/crud.service.ts file:

import { Injectable } from '@angular/core';
import { Book } from './Book';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class CrudService {
  // Node/Express API
  REST_API: string = 'http://localhost:8000/api';
  // Http Header
  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(private httpClient: HttpClient) { }
  // Add
  AddBook(data: Book): Observable<any> {
    let API_URL = `${this.REST_API}/add-book`;
    return this.httpClient.post(API_URL, data)
      .pipe(
        catchError(this.handleError)
      )
  }
  // Get all objects
  GetBooks() {
    return this.httpClient.get(`${this.REST_API}`);
  }
  // Get single object
  GetBook(id:any): Observable<any> {
    let API_URL = `${this.REST_API}/read-book/${id}`;
    return this.httpClient.get(API_URL, { headers: this.httpHeaders })
      .pipe(map((res: any) => {
          return res || {}
        }),
        catchError(this.handleError)
      )
  }
  // Update
  updateBook(id:any, data:any): Observable<any> {
    let API_URL = `${this.REST_API}/update-book/${id}`;
    return this.httpClient.put(API_URL, data, { headers: this.httpHeaders })
      .pipe(
        catchError(this.handleError)
      )
  }
  // Delete
  deleteBook(id:any): Observable<any> {
    let API_URL = `${this.REST_API}/delete-book/${id}`;
    return this.httpClient.delete(API_URL, { headers: this.httpHeaders}).pipe(
        catchError(this.handleError)
      )
  }
  // Error
  handleError(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Handle client error
      errorMessage = error.error.message;
    } else {
      // Handle server error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(errorMessage);
  }
}

Step 7 – Add code In app.component.html

In the step, you need to create HTML and for crud app in Angular. You need to visit src/app/app.component.html and update the below code into the HTML file:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand">Angular 13 CRUD Operations Demo</a>
  <div id="navbarNav" class="collapse navbar-collapse">
    <ul class="navbar-nav ml-auto ">
      <li class="nav-item">
        <a class="nav-link" routerLinkActive="active" routerLink="/books-list">Show Books</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" routerLinkActive="active" routerLink="/add-book">Add Books</a>
      </li>
    </ul>
  </div>
</nav>
<router-outlet></router-outlet>

Step 8 – Create Operation

After that, you can add the code in the add-book.component.ts file:

import { Component, OnInit, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { CrudService } from './../../service/crud.service';
import { FormGroup, FormBuilder } from "@angular/forms";
@Component({
  selector: 'app-add-book',
  templateUrl: './add-book.component.html',
  styleUrls: ['./add-book.component.scss']
})
export class AddBookComponent implements OnInit {
  bookForm: FormGroup;
  
  constructor(
    public formBuilder: FormBuilder,
    private router: Router,
    private ngZone: NgZone,
    private crudService: CrudService
  ) {
    this.bookForm = this.formBuilder.group({
      name: [''],
      price: [''],
      description: ['']
    })
  }
  ngOnInit() { }
  onSubmit(): any {
    this.crudService.AddBook(this.bookForm.value)
    .subscribe(() => {
        console.log('Data added successfully!')
        this.ngZone.run(() => this.router.navigateByUrl('/books-list'))
      }, (err) => {
        console.log(err);
    });
  }
}

Then, you need to add the following code in the add-book.component.html file:

<div class="row justify-content-center mt-5">
    <div class="col-md-4">
        <form [formGroup]="bookForm" (ngSubmit)="onSubmit()">
          <div class="form-group">
            <label>Name</label>
            <input class="form-control" type="text" formControlName="name" required>
          </div>
  
          <div class="form-group">
            <label>Price</label>
            <input class="form-control" type="text" formControlName="price" required>
          </div>
  
          <div class="form-group">
            <label>Description</label>
            <input class="form-control" type="text" formControlName="description" required>
          </div>
  
          <div class="form-group">
            <button class="btn btn-primary btn-block" type="submit">Add Book</button>
          </div>
        </form>
    </div>
  </div>

Next, you add the below code in the books-list.component.ts file:

import { Component, OnInit } from '@angular/core';
import { CrudService } from './../../service/crud.service';
@Component({
  selector: 'app-books-list',
  templateUrl: './books-list.component.html',
  styleUrls: ['./books-list.component.scss']
})
export class BooksListComponent implements OnInit {
  
  Books:any = [];
  constructor(private crudService: CrudService) { }
  ngOnInit(): void {
    this.crudService.GetBooks().subscribe(res => {
      console.log(res)
      this.Books =res;
    });   
  }
  delete(id:any, i:any) {
    console.log(id);
    if(window.confirm('Do you want to go ahead?')) {
      this.crudService.deleteBook(id).subscribe((res) => {
        this.Books.splice(i, 1);
      })
    }
  }
}

Next, you add the below code in the books-list.component.html file:

<div class="container">
  <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h2 class="h2">Books List</h2>
  </div>
  <div class="table-responsive">
    <table class="table table-bordered">
      <thead>
        <tr>
          <th scope="col">Id</th>
          <th scope="col">Name</th>
          <th scope="col">Price</th>
          <th scope="col">Description</th>
          <th class="text-center" scope="col">Action</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let book of Books; let i = index">
          <th scope="row">{{book._id}}</th>
          <td>{{book.name}}</td>
          <td>{{book.price}}</td>
          <td>{{book.description}}</td>
          <td class="text-center">
            <button class="btn btn-sm btn-primary" routerLink="/edit-book/{{book._id}}">Edit</button>
            <button class="btn btn-sm btn-danger" (click)="delete(book._id, i)">Delete</button>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Next, add the below code in the book-detail.component.ts file:

import { Component, OnInit, NgZone } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { CrudService } from './../../service/crud.service';
import { FormGroup, FormBuilder } from "@angular/forms";
@Component({
  selector: 'app-book-detail',
  templateUrl: './book-detail.component.html',
  styleUrls: ['./book-detail.component.scss']
})
export class BookDetailComponent implements OnInit {
  getId: any;
  updateForm: FormGroup;
  
  constructor(
    public formBuilder: FormBuilder,
    private router: Router,
    private ngZone: NgZone,
    private activatedRoute: ActivatedRoute,
    private crudService: CrudService
  ) {
    this.getId = this.activatedRoute.snapshot.paramMap.get('id');
    this.crudService.GetBook(this.getId).subscribe(res => {
      this.updateForm.setValue({
        name: res['name'],
        price: res['price'],
        description: res['description']
      });
    });
    this.updateForm = this.formBuilder.group({
      name: [''],
      price: [''],
      description: ['']
    })
  }
  ngOnInit() { }
  onUpdate(): any {
    this.crudService.updateBook(this.getId, this.updateForm.value)
    .subscribe(() => {
        console.log('Data updated successfully!')
        this.ngZone.run(() => this.router.navigateByUrl('/books-list'))
      }, (err) => {
        console.log(err);
    });
  }
}

Next, add the below code in the book-detail.component.html file:

<div class="row justify-content-center mt-5">
  <div class="col-md-4">
    <form [formGroup]="updateForm" (ngSubmit)="onUpdate()">
      <div class="form-group">
        <label>Name</label>
        <input class="form-control" type="text" formControlName="name" required>
      </div>
      <div class="form-group">
        <label>Price</label>
        <input class="form-control" type="text" formControlName="price" required>
      </div>
      <div class="form-group">
        <label>Description</label>
        <input class="form-control" type="text" formControlName="description" required>
      </div>
      <div class="form-group">
        <button class="btn btn-primary btn-block" type="submit">Update</button>
      </div>
    </form>
  </div>
</div>

For the topic of Angular 13 CRUD application using Node.js, Express.js, and MongoDB. In the tutorial, we introduce how to create a crud app in Angular 13 using Node js and Mongo DB with built REST API.

How to use Kong to make Orchestration Microservice API Gateway

Kong is an Orchestration Microservice API Gateway. Kong is an abstraction layer that manages client-microservice communication securely via APIs. It is sometimes called an API Gateway, API Middleware, or Service Mesh. In 2015, it became an open-source project, and its core values are high performance and extensibility.

Kong runs in Nginx as a Lua application and is enabled by Lua-Nginx-module.

Why use Kong?

If you need a common functionality to run your actual software on your website, mobile, or IoT (Internet of Things). Kong can work as a gateway (sidecar) for microservices requests, at the same time also possible to provide logging, load balancing, authentication, rate-limiting, transformations, and more through plugins.

Kong can work as a gateway (sidecar) for microservices requests

Kong also helps you to shorten development time, and support configurable plugins. It has many communities to support your development and make it stable.

Kong can add Security plugins for security layers such as ACL, CORS, Dynamic SSL, IP Restriction. It also has a useful traffic control plugin that has limited costs such as rate-limiting, request size limiting, response rate-limiting...

Support Analytics and monitoring plugin which can visualize, inspect, monitor traffic including Prometheus, data dog, and Runscope.

Support transforms requests and responses on the fly including Request Transformer, Response Transformer by Transformation plugin

Support logging request and response data using: TCP, UDP, HTTP, StatsD, Syslog, and others by Logging plugin

Here we will make a tutorial on how to set up and use KONG. You should refer to Docker and API REST for needed knowledge.

How to Install Kong Community Edition

Kong can work in multiple operating environments. The easiest installation is using docker. Follow the instruction below to install by docker.

Install KONG by docker

1. Create a docker network for Kong and API server

$ docker network create kong-net

2. Run a database. You can choose Postgres or Cassandra. We prioritize Postgres

$ docker run -d --name kong-database \
--network=kong-net \
-p 5555:5432 \
-e “POSTGRES_USER=kong” \
-e “POSTGRES_DB=kong” \
postgres:9.6

3. Run migration with Kong container after preparing a database

$ docker run --rm \
--network=kong-net \
-e “KONG_DATABASE=postgres” \
-e “KONG_PG_HOST=kong-database” \
kong:latest kong migrations up

4. After the migrations and database have been complete, start Kong container

$ docker run -d --name kong \
--network=kong-net \
-e “KONG_LOG_LEVEL=debug” \
-e “KONG_DATABASE=postgres” \
-e “KONG_PG_HOST=kong-database” \
-e “KONG_PROXY_ACCESS_LOG=/dev/stdout” \
-e “KONG_ADMIN_ACCESS_LOG=/dev/stdout” \
-e “KONG_PROXY_ERROR_LOG=/dev/stderr” \
-e “KONG_ADMIN_ERROR_LOG=/dev/stderr” \
-e “KONG_ADMIN_LISTEN=0.0.0.0:8001, 0.0.0.0:8444 ssl” \
-p 9000:8000 \
-p 9443:8443 \
-p 9001:8001 \
-p 9444:8444 \
kong:latest

4. Using the request cmd to check Kong Instance

$ curl -i http://localhost:9001

The successful response is

HTTP/1.1 200 OK
Server: openresty/1.13.6.2
Date: Wed, 18 Jul 2018 03:58:57 GMT
Content-Type: application/json
Connection: keep-alive
Access-Control-Allow-Origin: *

Now Kong is run completely. The next task is that prepare an API server containing service routes and support REST API.

Use node.js to setup API server routing

In the task, we will use node.js for an API server. For simple, you 
can clone from GitHub faren-NodeJS-API-KONG. And it should contain like this in terminal:
Now prepare the API server, for this tutorial we are going to use node.js as an API server. To make it simple, please clone the code from GitHub faren-NodeJS-API-KONG. It should contain like below:
$ ls -l
total 48
-rw-r — r — 1 farendev staff 186 Jul 18 11:37 Dockerfile
-rw-r — r — @ 1 farendev staff 31716 Jul 16 10:36 Kong.postman_collection.json
-rw-r — r — 1 farendev staff 100 Jul 18 11:37 README.md
-rw-r — r — 1 farendev staff 878 Jul 18 11:37 index.js
-rw-r — r — 1 farendev staff 307 Jul 18 11:37 package.json

Let’s build a docker image and run it, by the cmd below:

$ docker build -t node_kong .
$ docker run -d --name=node_kong --network=kong-net node_kong

Check all docker has been run by cmd below:

$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d13586f83e52 node_kong “npm start” 2 minutes ago Up 2 minutes 10000/tcp node_kong
41156cad5c86 kong:latest “/docker-entrypoint.…” 6 days ago Up 6 days 0.0.0.0:9000->8000/tcp, 0.0.0.0:9001->8001/tcp, 0.0.0.0:9443->8443/tcp, 0.0.0.0:9444->8444/tcp kong
f794a0e9506c postgres:9.6 “docker-entrypoint.s…” 6 days ago Up 6 days 0.0.0.0:5555->5432/tcp kong-database

Get an IP container on the docker network kong-net for checking API server by accessing its API. You can get into the container kong shell and check the API from it.

Execute the cmd bellow on your terminal:

$ docker network inspect kong-net
…
…
“Containers”: {
“41156cad5c864af4ad8615c051fac8da7f683238a6c8cc42267f02813f14810f”: {
“Name”: “kong”,
“EndpointID”: “fe1cec9f6f31a015ab29a100fdd54b609abea11bbfa00f5e9ca67cc6175d7b2f”,
“MacAddress”: “02:42:ac:13:00:03”,
“IPv4Address”: “172.19.0.3/16”,
“IPv6Address”: “”
},
“d13586f83e52df8866b9879ba0537d58c21fc1b95978dde0580b017ce1a7b418”: {
“Name”: “node_kong”,
“EndpointID”: “5677f7588b7daef391cf8cecec6a3ede0155f99f7d86e0e14dd5970ff0570924”,
“MacAddress”: “02:42:ac:13:00:04”,
“IPv4Address”: “172.169.0.5/16”,
“IPv6Address”: “”
},
“f794a0e9506c7330f1cc19c5c390f745823c29dd4603e0d727dae4e8a68caa8d”: {
“Name”: “kong-database”,
“EndpointID”: “51737ca4e2a4b0e30d25db86e197e653a81e6206893588f4dae7b4a0a50e2799”,
“MacAddress”: “02:42:ac:13:00:02”,
“IPv4Address”: “172.19.0.2/16”,
“IPv6Address”: “”
}
},
…

Check the IP on node_kong in bold font and execute curl the IP bellow exactly.

$ docker exec -ti kong sh
/ # curl -i 172.169.0.5:10000/api/v1/customers
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 110
ETag: W/”6e-Tf3vAGLC3XH0dFR2pCIzWdG8/5c”
Date: Wed, 18 Jul 2018 10:09:32 GMT
Connection: keep-alive
[{“id”:5,”first_name”:”Dodol”,”last_name”:”Dargombez”},{“id”:6,”first_name”:”Nyongot”,”last_name”:”Gonzales”}]

The above respond shows that server API is alive, and can serve to GET method REST /API/v1/workers.

How to setup KONG as API – Gateway to API server routing

After completing the KONG engine and node.js API service, and starting registering our API to Kong, the image below shows the workflow.

Routes define rules to match client requests and work as entry points in Kong. When a route is matched, Kong proxies the request to its associated Service. The service will be direct to the API server that is ready to serve.

For example (Warning: IP might very different for every machine)

API server that is live on server http://172.169.0.5:10000/api/v1/customers

We set routes path /api/v1/customers

And set the service host to http://172.169.0.5:10000, and path /api/v1/customers

So, when the client request to kong (in this case kong is life at localhost:9000) with path route /api/v1/customer: incomplete client request http://localhost:9000/api/v1/customers , Kong will proxy it to 172.169.0.5:10000/api/v1/customers

To start please import postman collection file on GitHub NodeJS-API-KONG (https://github.com/faren/NodeJS-API-KONG) — kong.postman_collection.json.

So let’s see in practice take a look postman collection that has been imported:

For this tutorial, we should get the result like the above scenario:

REST for customers and clients.

Firstly, you register service customers and then register match routes requested. Let take a look at how to get node_kong IP from the docker network.

Find collection Kong, folder Services, POST Services — Create:

POST: localhost:9001/services/

Headers: Content-Type:application/json
Body:
{
“name”: “api-v1-customers”,
“url”: “http://172.169.0.5:10000/api/v1/customers"
}Respond:
{
“host”: “172.169.0.5”,
“created_at”: 1531989815,
“connect_timeout”: 60000,
“id”: “d28c20e4–94d3–4c3b-9a0d-688ac8dbf213”,
“protocol”: “http”,
“name”: “api-v1-customers”,
“read_timeout”: 60000,
“port”: 10000,
“path”: null,
“updated_at”: 1531989815,
“retries”: 5,
“write_timeout”: 60000
}

Find collection Kong, folder Services, GET Services — List:

GET: localhost:9001/services/

Respond:
{
“next”: null,
“data”: [
{
“host”: “172.169.0.5”,
“created_at”: 1531989815,
“connect_timeout”: 60000,
“id”: “d28c20e4–94d3–4c3b-9a0d-688ac8dbf213”,
“protocol”: “http”,
“name”: “api-v1-customers”,
“read_timeout”: 60000,
“port”: 10000,
“path”: null,
“updated_at”: 1531989815,
“retries”: 5,
“write_timeout”: 60000
}
]
}

After creating service customers, you can create routes for service customers.

Find collection Kong, folder Routes, POST Routes — Create:

POST: localhost:9001/services/api-v1-customers/routes/

Headers: Content-Type:application/json
Body:
{
“hosts”: [“api.ct.id”],
“paths”: [“/api/v1/customers”]
}Respond:
{
“created_at”: 1531991052,
“strip_path”: true,
“hosts”: [
“api.ct.id”
],
“preserve_host”: false,
“regex_priority”: 0,
“updated_at”: 1531991052,
“paths”: [
“/api/v1/customers”
],
“service”: {
“id”: “d28c20e4–94d3–4c3b-9a0d-688ac8dbf213”
},
“methods”: null,
“protocols”: [
“http”,
“https”
],
“id”: “4d9503c3-d826–43e3–9063-ed434a949173”
}

Find collection Kong, folder Routes, GET Routes -> List:

GET: localhost:9001/services/

Respond:
{
“next”: null,
“data”: [
{
“created_at”: 1531991052,
“strip_path”: true,
“hosts”: [
“api.ct.id”
],
“preserve_host”: false,
“regex_priority”: 0,
“updated_at”: 1531991052,
“paths”: [
“/api/v1/customers”
],
“service”: {
“id”: “d28c20e4–94d3–4c3b-9a0d-688ac8dbf213”
},
“methods”: null,
“protocols”: [
“http”,
“https”
],
“id”: “4d9503c3-d826–43e3–9063-ed434a949173”
}
]
}

Check you can access API customers from KONG (http://localhost:9000/api/v1/customers)

GET: localhost:9000/api/v1/customers

Headers: Host:api.ct.id
Respond:
[
{
“id”: 5,
“first_name”: “Dodol”,
“last_name”: “Dargombez”
},
{
“id”: 6,
“first_name”: “Nyongot”,
“last_name”: “Gonzales”
}
]

Conclusion

Kong is an open-source, scalable API Layer (API Gateway, or API Middleware), which runs in front of any RESTful API and is extended through Plugins. Kong can provide extra functionality and services beyond the core platform.

For better understanding, the image below shows a typical request workflow of an API using Kong:

When Kong is running, every request being made to the API will hit Kong first, and then it will be proxied to the final API. Kong can execute any plugin in between requests and responses. You can install many types of plugins to empower your APIs, Kong is also supported by plugins from authentication, security, traffic control, logging, and etc… Kong can be used effectively as entry points for every API request.

Angular 13 Spring WebFlux MongoDB CRUD Operations

In this tutorial, we’re gonna build a full Reactive Application in which, Spring WebFlux, Spring Data Reactive MongoDB are used for backend, and Angular, RxJS, EventSource are on client side.

Related Posts:
How to use Angular Http Client to fetch Data from SpringBoot RestAPI – Angular 13
How to use Angular HttpClient to POST, PUT, DELETE data on SpringBoot Rest APIs – Angular 13
How to build SpringBoot MongoDb RestfulApi
How to use SpringData MongoRepository to interact with MongoDB
Angular 13 + Spring Boot + MongoDB CRUD example
Introduction to RxJS – Extensions for JavaScript Reactive Streams

Continue reading “Angular 13 Spring WebFlux MongoDB CRUD Operations”

How to Integrate Angular 13 & SpringBoot 2.0 RestAPI – SpringToolSuite

In the tutorial, we show you how to integrate Angular 13 with SpringBoot RestAPI for development using SpringToolSuite IDE.

Related posts:
Angular 13 Component – How to create & integrate New Angular 13 Component
Angular 13 Service – with Observable Data for Asynchronous Operation

Spring Boot + Angular 13 example | Spring Data JPA + REST + PostgreSQL CRUD example
Spring Boot + Angular 13 example | Spring Data JPA + REST + MySQL CRUD example
Angular 13 HttpClient + Spring Boot + MariaDB example | Spring Data JPA + RestAPIs CRUD example
Spring Boot + Angular 13 example | Spring Data + REST + MongoDb CRUD example
Spring Boot + Angular 13 example | Spring Data + REST + Cassandra CRUD example

Continue reading “How to Integrate Angular 13 & SpringBoot 2.0 RestAPI – SpringToolSuite”

Angular 13 SpringBoot CRUD Mariadb Example

In this tutorial, we show you Angular 13 Http Client & Spring Boot Server example that uses Spring JPA to do CRUD with MariaDB and Angular 13 as a front-end technology to make request and receive response.

Related Posts:
Spring Boot + Angular 13 example | Spring Data JPA + REST + MySQL CRUD example
Spring Boot + Angular 13 example | Spring Data JPA + REST + PostgreSQL CRUD example
Spring Boot + Angular 13 example | Spring Data + REST + Cassandra CRUD example
How to use Spring JPA with PostgreSQL | Spring Boot

Related Pages:

Continue reading “Angular 13 SpringBoot CRUD Mariadb Example”