Dylan North

Dylan North


Generating and Consuming REST APIs with Spring Boot 2, Angular 7 and Swagger 2

Originally published by Swathi Prasad at Medium 

Imagine you want to integrate backend APIs or third party APIs with minimal effort, how do you pull it off?

Integrating Backend APIs manually can be time consuming and error-prone. Hence, Swagger comes into picture. Swagger is the most popular framework to generate and consume OpenAPI specification. The tool greatly relieves the burden of documenting and interacting with APIs.

In this article, we are going to generate API documentation from Spring Boot REST API and generate Angular API client from the documentation using Swagger.

Tools and Technologies Used

  • Spring Boot — 2.1.4.RELEASE
  • JDK — OpenJDK 12
  • Spring Framework — 5.1.6 RELEASE
  • JPA
  • Hibernate
  • H2 in-memory database
  • Swagger — 2
  • springfox-swagger2–2.9.4
  • springfox-swagger-ui — 2.9.4
  • Swagger Codegen CLI — 2.4.4
  • IDE — IntelliJ and Visual Studio Code
  • Angular CLI — 7.2.0
  • Node — 8.11.3
  • NPM — 6.3.0

Generating Swagger API Documentation

Create a sample Spring Boot application. Here is my sample project structure. I have created the project manually, but you could also create using Spring Intializer.

I will go over each package in a bit.

Spring Boot Project Structure

There are several implementations of Swagger 2 which adheres to Open API specification. Springfox is one of those implementations. Currently, Springfox supports only Swagger 1.2 and Swagger 2.0. Add Springfox dependencies as follows:


Here is the complete Maven POM.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    &lt;relativePath /&gt;




Let us first enable Swagger support in the application. We enable using 

@EnableSwagger2 annotation. Notice that we are specifying base package “com.swathisprasad.springboot”. This is to generate API documentation within our custom package.

If we do not provide base package, Swagger would generate documentation even for Spring Boot actuator endpoints which may not be of our interest.

package com.swathisprasad.springboot.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

public class SwaggerConfig {

public Docket api() {

    return new Docket(DocumentationType.SWAGGER_2).select()

private ApiInfo apiEndPointsInfo() {

    return new ApiInfoBuilder().title("Spring Boot REST API")
            .description("Language Management REST API")
            .contact(new Contact("Swathi Prasad", "www.techshard.com", "techshard08@gmail.com"))
            .license("Apache 2.0")


Before we create an API endpoint, let’s create a JPA entity Language and a corresponding JPA repository ILanguageRepository. I have also created a DataInitializer class to create mock data at server startup.

package com.swathisprasad.springboot.dao.entity;

import javax.persistence.*;

public class Language {

@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

private String name;

public Language() {

public String getName() {
    return name;

public void setName(final String name) {
    this.name = name;

public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result + (int) (id ^ (id &gt;&gt;&gt; 32));
    return result;

public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (!(obj instanceof Language))
        return false;
    final Language other = (Language) obj;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    return true;

package com.swathisprasad.springboot.dao.repository;

import com.swathisprasad.springboot.dao.entity.Language;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

public interface ILanguageRepository extends JpaRepository<Language, Long> {
package com.swathisprasad.springboot;

import com.swathisprasad.springboot.dao.entity.Language;
import com.swathisprasad.springboot.dao.repository.ILanguageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class DataInitializer {

private final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

ILanguageRepository languageRepository;

public void initData() {

    try {
        Language language = new Language();

        language = new Language();

        language = new Language();

        language = new Language();

        language = new Language();

        language = new Language();

    } catch (final Exception ex) {
        logger.error("Exception while inserting mock data {}", ex);



Create a REST controller which contains an API endpoint as below. We can customize API documentation using @API, @APIOperation and @APIResponse annotations provided by Springfox as shown below.

package com.swathisprasad.springboot.controller;

import com.swathisprasad.springboot.dao.entity.Language;
import com.swathisprasad.springboot.dao.repository.ILanguageRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(value=“Language API”, description=“Operations pertaining to Language”)
public class LanguageController {

ILanguageRepository languageRepository;

@ApiOperation(value = "View a list of available languages", response = Iterable.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully retrieved list"),
        @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
        @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
        @ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
@GetMapping(value = "/languages", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity&lt;List&lt;Language&gt;&gt; getLanguages() {
    final List&lt;Language&gt; languages = languageRepository.findAll();
    return new ResponseEntity&lt;&gt;(languages, HttpStatus.OK);


Now, let us run Application class as Java application. Note that we will see below warning when Undertow server is started. Undertow complains about XNIO Illegal reflective access since Java 9+ and the issue has been reported here.

WARNING: An illegal reflective access operation has occurred

Once the server has started successfully, open http://localhost:8080/v2/api-docs in the browser. We will see Swagger documentation and save it as JSON on your file system.

This documentation adheres to OpenAPI 2.0 specification.

The Swagger UI can be viewed at http://localhost:8080/swagger-ui.html .

NOTE: If you wish to generate OpenAPI 3.0 spec, the above generated spec can also be imported and converted into OpenAPI 3.0 spec at SwaggerHub.

Generating Angular API Clients with Swagger

The biggest advantage of generated API clients would save a lot of time from writing Angular services and model manually. Let us see how it can be achieved.

In this tutorial, we will use Swagger Codegen library to generate API clients. The library can be downloaded directly from Maven Repository.

Swagger Codegen 2.x supports OpenAPI Spec 2.0 and 3.x supports both OpenAPI spec 2.0 and 3.0. Since our Swagger spec is compliant to OpenAPI spec 2.0, we will use Swagger Codegen 2.x for generating API client.

Download the jar file from Maven repository. Open the command prompt or terminal and run the following command. If you are on windows, remove the backslashes and write the entire command in single line.

java -jar swagger-codegen-cli-2.4.4.jar generate -i api-docs.json </em>
-l typescript-angular </em>
-o angular-client </em>
— additional-properties npmName=@techschard/language-api,snapshot=true,ngVersion=7.2.0
  • -i or –input-spec defines the location of the input swagger spec, as URL or file (required)
  • -l or –lang defines the client language to generate (required)
  • -o or –output defines the output directory, where the generated files should be written to (current directory by default)
  • -c or –config defines the path to an additional JSON configuration file. Supported options can be different for each language. We will look at this argument in the paragraph.

Note that the — additional-properties is added to generate the client as an Angular package. These properties can also be provided via a config file through -c or — config parameter.

The detailed explanation can be found via the following command.

java -jar swagger-codegen-cli.jar help generate

The generated file structure would be as follows:

Here, the .ng_pkg_build directory and ng-package.json can be ignored for now. They are not generated by Swagger Codegen.

This is a complete Angular project with all required configuration files and typescript files to create an angular (ng) package. I have published the generated Angular package to npm. Let us see how to publish to npm.

Publish Angular Package to NPM

Login to NPM and create a new user account if you don’t have one. In the terminal or command prompt, type npm adduser. Provide your new npm username and password. This is to authorize your machine to publish npm packages.

Run npm install in the above generated npm package. Then, run npm run build command.

We might have to install tsickle module as required by npm packager module. Install the module if necessary.

Finally, run npm publish dist — access=public command to publish to npm repository.

Here, the — access=public makes the repository public. By, default the repository would be set to restricted.

Once it is published, you will find your package under your account as below.

Consuming API Clients with Swagger

Now that we have generated API client and uploaded it to NPM, we will create a small Angular project through Angular CLI and include the generated API client.

Run the following command in terminal to create a new Angular project.

ng new angular7-swagger

Once the project is created, install the following npm module within the project.

npm install @techshard/language-rest-api

Here, language-rest-api is the npm package that contains our generated Angular.

Edit the app.module.ts file and include this npm package. Here is the complete file.

import { BrowserModule } from ‘@angular/platform-browser’;

import { NgModule } from ‘@angular/core’;

import { ApiModule, BASE_PATH } from ‘@techshard/language-rest-api’;

import { HttpClientModule } from ‘@angular/common/http’;

import { environment } from ‘./…/environments/environment’;

import { AppRoutingModule } from ‘./app-routing.module’;

import { AppComponent } from ‘./app.component’;

import { LanguageComponent } from ‘./language/language.component’;


declarations: [




imports: [






providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }],

bootstrap: [AppComponent]


export class AppModule { }

Let’s create a new module “language” and import generated service and data model in this new component. Then, we will call the API to retrieve the list of languages.

import { Component, OnInit } from ‘@angular/core’;

import { LanguageControllerService, Language } from ‘@techshard/language-rest-api’;


selector: ‘app-language’,

templateUrl: ‘./language.component.html’,

styleUrls: [‘./language.component.scss’]


export class LanguageComponent implements OnInit {

languages: Language[] = [];

constructor(private languageControllerService: LanguageControllerService) { }

ngOnInit() {

this.languageControllerService.getLanguagesUsingGET().subscribe(res => {

for (var i in res) {






The language.component.html shall be modified as follows to display the list of languages.


*ngFor=“let l of languages; index as i” class=“panel-body”>

<a class=“text-success”>{{l.name}}</a>


Now, edit the app.component.html and add the language template. The complete HTML file is here:

<div class=“container blue”>

<div class=“page-header”>

<nav class=“navbar navbar-inverse”>

<div class=“container-fluid”>

<div class=“navbar-header”>

<a class=“navbar-brand” href=“https://en.wikipedia.org/wiki/List_of_programming_languages”>

List of programming languages</a>





<div class=“col-md-2”>



<div class=“col-md-9”>




Note that I have installed Bootstrap 4 and imported into the project.

Running the Angular App

Run the following command in the terminal.

ng serve

Once the project is compiled successfully, open http://localhost:4200 in the browser and we will see list of languages as follows:


Congratulations! We have learned to automatically generate and consume API code. This approach reduces errors and writing a lot of boilerplate code. Also, this approach can be very useful for developing Micro Frontends.

The complete source code can be found on my GitHub repository.

I hope you enjoyed my article. Feel free to leave any comments or suggestions.

Happy learning!


Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ JavaScript Bootcamp - Build Real World Applications

☞ The Web Developer Bootcamp

☞ JavaScript: Understanding the Weird Parts

☞ Building a Simple URL Shortener With Just HTML and Javascript

☞ The JavaScript Developer’s Guide To Node.JS

☞ From Javascript to Typescript to Elm

☞ Google’s Go Essentials For Node.js / JavaScript Developers

☞ 3 things you didn’t know about the forEach loop in JavaScript

#javascript #angular #spring-boot #typescript

What is GEEK

Buddha Community

Generating and Consuming REST APIs with Spring Boot 2, Angular 7 and Swagger 2
Wilford  Pagac

Wilford Pagac


What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.


If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Sigrid  Farrell

Sigrid Farrell


Angular 12 + Spring Boot: CRUD example

In this tutorial, we will learn how to build a full stack Spring Boot + Angular 12 example with a CRUD App. The back-end server uses Spring Boot with Spring Web MVC for REST Controller and Spring Data JPA for interacting with embedded database (H2 database). Front-end side is made with Angular 12, HttpClient, Router and Bootstrap 4.

Run both Project on same server/port:

How to Integrate Angular with Spring Boot Rest API

Contents [hide]

#angular #full stack #spring #angular #angular 12 #crud #h2 database #mysql #postgresql #rest api #spring boot #spring data jpa

Sigrid  Farrell

Sigrid Farrell


Angular 12 + Spring Boot + PostgreSQL example: Build CRUD App

In this tutorial, we will learn how to build a full stack Angular 12 + Spring Boot + PostgreSQL example with a CRUD App. The back-end server uses Spring Boot with Spring Web MVC for REST Controller and Spring Data JPA for interacting with PostgreSQL database. Front-end side is made with Angular 12, HTTPClient, Router and Bootstrap 4.

Older versions:

– Angular 10 + Spring Boot + PostgreSQL example: CRUD App

– Angular 11 + Spring Boot + PostgreSQL example: CRUD App

Contents [hide]

#angular #full stack #spring #angular #angular 12 #crud #postgresql #rest api #spring boot #spring data jpa