DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Difference Between Bootstrap and AngularJS in 2022
  • 4 Common Bugs in Angular (and How to Fix Them)
  • A Systematic Approach for Java Software Upgrades
  • Implementing Micro Frontends in Angular: Step-By-Step Guide

Trending

  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • Unlocking AI Coding Assistants Part 4: Generate Spring Boot Application
  • A Guide to Developing Large Language Models Part 1: Pretraining
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  1. DZone
  2. Coding
  3. Frameworks
  4. Using Swagger to Connect a Backend to an Angular Frontend

Using Swagger to Connect a Backend to an Angular Frontend

Learn how you can use Swagger to ease the creation of an Angular front-end based on an existing set of RESTful services- everyone wants to make their lives easier!

By 
Brian Fernandes user avatar
Brian Fernandes
·
Oct. 19, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
40.3K Views

Join the DZone community and get the full member experience.

Join For Free

Let’s say you have an advanced backend system, for which you wish to develop a modern Angular frontend, or, perhaps it’s not your backend, but something public like Facebook, and you want to develop a site using some of its exposed APIs. Of course, you want to do this with minimal effort … how do you pull this off? Enter Swagger!

This article will walk you through the key steps required to connect an existing Java EE backend, which already exposes RESTful services, to an Angular frontend. Once you understand how these dots are connected, you can follow similar steps for other backends, or public APIs too.

Would you rather learn how to do this visually instead of reading this article? If yes, jump ahead to the Webinar we presented on this subject last week.

Broad Strokes

To connect our existing backend to an Angular frontend, we’re going to perform the following steps:

  1. Generate a Swagger/OpenAPI specification file for your backend
  2. Generate frontend code from the Swagger specification file
  3. Create an Angular App to use the generated code

Generating a Swagger Specification File for Your Java EE Backend

Note that we’re starting with an application that already exposes RESTful web services through JAX-RS. If your application does not already do this, you must first create services which expose data that the frontend needs to function – this is beyond the scope of this article.

You can follow along with this project or your own.

  1. Add Swagger dependencies to our project, we’re adding swagger-core, swagger-jaxrs and swagger-annotations which are libraries that cover the annotations we’re going to add to our code, interaction with JAX-RS, and generation of the Swagger specification file. If you’re using Maven, the dependencies look like this:
  2. <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-core</artifactId>
        <version>1.5.13</version>
    </dependency>
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-jaxrs</artifactId>
        <version>1.5.13</version>
    </dependency>
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.5.13</version>
    </dependency>


  3. Add @Api annotations to resourcesWhat we want to do here is identify our REST resources which we wish to expose further with Swagger, and annotate them with the @Api (io.swagger.annotations.Api) annotation. See the following screenshot for an example:swagger-ss-1We must do this for all resources that we want to be exposed. Note: There are several other annotations that will allow you to document and customize the specification file generated, among other things. Please see this document for more details.
  4. Add specification generation code in the root of your application (or any other appropriate place) add the following code to generate the Swagger specification file. Note that the URLs I’ve used are specific to our demo application.
  5. BeanConfig beanConfig = new BeanConfig();
    beanConfig.setVersion("2.0.0");
    beanConfig.setSchemes(new String[]{"http"});
    beanConfig.setHost("localhost:8080");
    beanConfig.setBasePath("/applicationPetstore/rest");
    beanConfig.setResourcePackage("org.agoncal.application.petstore.rest");
    beanConfig.setPrettyPrint(true);
    beanConfig.setScan();
  6. When this application is deployed, navigate over to http://localhost:8080/applicationPetstore/rest/swagger.json to get your Swagger specification file. It should look somewhat like this: swagger-ss-2-changed

Generating Frontend Code From the Swagger Specification File

In this part, we’ll take the swagger specification file generated in the previous section, and generate some code that we can use in our Angular frontend. We’ll use the Swagger Code Generator to generate this code.

  1. Use this link to download version 2.2.3 of this tool: http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.3/swagger-codegen-cli-2.2.3.jar

    Do check if a more recent version is available before downloading.
  2. From the command line, execute the following command:java -jar swagger-codegen-cli-2.2.3.jar generate -i
    http://localhost:8080/applicationPetstore/rest/swagger.json -l typescript-angular2

    Note that we are pointing to the same Swagger specification we obtained in the last section. The output of this command is a number of TypeScript files, including models and API code. The models in the model folder are a representation of your RESTful resources in TypeScript. The API code in the api folder is responsible for actually making the calls to the exposed endpoints, and dealing with the responses returned.

Create an Angular App to Use the Generated Code

With Angular IDE or MyEclipse, creating an Angular application is easy, even if you don’t have Node, NPM or the Angular CLI installed – we’ll download everything for you as part of the project creation process.

Following are a few highlights, covering Angular project creation, as well as key pieces of code. The code below can be found in this project.

swagger-ss-3

swagger-ss-4

Observe the following snippets of code which use the generated Category model as well as the CategoryApi class to display a list of categories. Of course, this code is specific to the Swagger specification file that we fed into the Swagger code generator.

swagger-ss-5

category-list.component.ts

export class CategoryListComponent implements OnInit {

  public categories: Category[] = [];

  constructor(private categoryApi: CategoryApi) {
  }

  ngOnInit() {
    this.categoryApi.listAll().subscribe(
      value => {
        setTimeout(() => this.categories.push(...value), 2000);
      },
      error => console.error(JSON.stringify(error)),
      () => console.log('done')
    );
  }
}

category-list.component.html

<div class="panel panel-success">
    <div class="panel-heading">
        Categories
    </div>
    <div class="panel-body">
        <strong *ngIf="categories.length == 0">Loading...</strong>
        <ul *ngIf="categories.length > 0" class="nav nav-pills nav-stacked">
            <li *ngFor="let category of categories" routerLinkActive="active">
                <a [routerLink]="'category/' + category.id">{{category.name}}</a>
            </li>
        </ul>
    </div>
</div>

More on Swagger?

For more info on what Swagger can do for you, check out our “Using APIs with Swagger” webinar which covers these topics in more detail.


Resources

Projects Referenced:
Backend Java EE 7 Project: Petstore Java EE 7
Frontend Angular Project: Petstore Frontend

IDEs Used:
Angular IDE: Optimized for developers to make the most of Angular, advanced validation, content assist, debugging and more.  
MyEclipse: A single Java IDE that includes the best tools for the full stack developer to create a dynamic frontend along with a powerful backend.

AngularJS Java EE dev application

Published at DZone with permission of Brian Fernandes, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Difference Between Bootstrap and AngularJS in 2022
  • 4 Common Bugs in Angular (and How to Fix Them)
  • A Systematic Approach for Java Software Upgrades
  • Implementing Micro Frontends in Angular: Step-By-Step Guide

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: