@ahmedesmat
Ahmed Esmat
Generating and Consuming REST APIs with Spring Boot 2, Angular 7 and Swagger 2Imagine 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.RELEASEJDK — OpenJDK 12 Spring Framework — 5.1.6 RELEASEJPAHibernateH2 in-memory databaseSwagger — 2springfox-swagger2 — 2.9.4springfox-swagger-ui — 2.9.4Swagger Codegen CLI – 2.4.4IDE — IntelliJ and Visual Studio CodeAngular CLI – 7.2.0Node – 8.11.3NPM – 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. 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: 
 io.springfox
 springfox-swagger2
 2.9.2
 
 
 io.springfox
 springfox-swagger-ui
 2.9.2
 Here is the complete Maven POM. 4.0.0 com.swathisprasad springboot-swagger 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.1.4.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.springframework.boot spring-boot-starter-undertow org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-data-jpa io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2 com.h2database h2 org.springframework.boot spring-boot-maven-plugin 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; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors .basePackage(com.swathisprasad.springboot)) .paths(PathSelectors.any()) .build().apiInfo(apiEndPointsInfo()); } 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) .licenseUrl(http://www.apache.org/licenses/LICENSE-2.0.html) .version(1.0-SNAPSHOT) .build(); } } 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.*; @Entity public class Language { @Id @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; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + (int) (id ^ (id >>> 32)); return result; } @Override 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; @Repository public interface ILanguageRepository extends JpaRepository { } 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; @Component public class DataInitializer { private final Logger logger = LoggerFactory.getLogger(DataInitializer.class); @Autowired ILanguageRepository languageRepository; public void initData() { try { Language language = new Language(); language.setName(Java); languageRepository.save(language); language = new Language(); language.setName(JavaScript); languageRepository.save(language); language = new Language(); language.setName(C++); languageRepository.save(language); language = new Language(); language.setName(Groovy); languageRepository.save(language); language = new Language(); language.setName(Python); languageRepository.save(language); language = new Language(); language.setName(Swift); languageRepository.save(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; @RestController @Api(value=Language API, description=Operations pertaining to Language) @RequestMapping(/api) public class LanguageController { @Autowired 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> getLanguages() { final List languages = languageRepository.findAll(); return new ResponseEntity<>(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 \ -l typescript-angular \ -o angular-client \ --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 package. Edit app.module.ts and import 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'; @NgModule({ declarations: [ AppComponent, LanguageComponent ], imports: [ BrowserModule, AppRoutingModule, ApiModule, HttpClientModule ], 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'; @Component({ 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) { this.languages.push(res[i]); } }); } } The language.component.html shall be modified as follows to display the list of languages. {{l.name}} Now, edit the app.component.html and add the language template. The complete HTML file is here: List of programming languages 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: App preview Conclusion 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!
1
We're Hiring a Part-time Photographer!We are looking to hire a joyful, creative, driven, big-hearted photographer. This is a part-time role, 3 days a week. We are fairly flexible on the scheduling which makes this role ideal for someone who is also running their own photo projects. In this role you will own and help evolve Tattly's visual language and work closely with the Design, Marketing and Custom team to execute on all of Tattly’s photography needs. Responsibilities include Photographing and retouching all of Tattly's brand imagery from applied shots to still life and product shots. Sourcing models and clothing/props for shoots. Collaborating on creative direction and execution of marketing campaigns and launches to increase Tattly awareness. Organizing and keeping track of Tattly assets on the server. Updating and reshooting outdated Tattly photos. Keeping the photo studio organized. Coordinating with every department to keep all press folders updated. Requirements You have strong photo retouching/compositing skills (Photoshop, Lightroom). You are able to provide your own camera and lenses. You have knowledge of different lighting setups, specifically alien bee lighting systems. You are resourceful and are comfortable working with a modest budget. You are able to take the lead on shoots, but also comfortable with collaboration. You love animated GIFs. We would be really excited if you have video editing skills. You are confident in who you are and in your talent, yet are humble and grateful by nature. You figure things out and you love a good challenge. You’re self-driven (tell us about your side projects) and excited to work with a hardworking and kind team. You are excited about helping us grow Tattly. You care and are excited about your contributions having an impact on the bottom line. You’re a big hearted human, joyful and kind. You are legally allowed to work in the US, and are excited to commute to our beautiful Boerum Hill Office every day. ENVIRONMENT Team Tattly is a friendly bunch and shares their working space with team CreativeMornings. We work door to door with the creative co-working space Friends Work Here. These are all companies started and run by our founder Tina Roth Eisenberg. If you want to learn more about her values and how she runs her companies, watch her 99U talk. Tina considers Tattly a labor of love, with which we are catapulting beautiful art and joy into the world. Tattly is not solving the world’s biggest problems, but we are putting smiles on people’s faces and helping support artists with our generous royalty. We are proud of that. Job Perks: Flexible scheduling (3 days per week) An endless supply of tattoos and snacks 24/7 confetti drawer access dog love with Ginger and Jack Charles If you think you are the perfect candidate for this role, please send us a thoughtful email in which you tell us a bit about yourself, why you’re a good match, what lights you up, what attracts you to our company. Please include a link to your portfolio, as well as link to your favorite Tattly design and a joke. Applications without a joke will not be considered. → jobs@tattly.com