SlideShare une entreprise Scribd logo
1  sur  44
@johannes_fiala#Devoxx #Swagger
Enhance existing REST APIs
(e.g. Facebook Graph API) with
code completion using
Swagger/Spring
Johannes Fiala
FWD
@johannes_fiala#Devoxx #Swagger
Enhance REST APIs
• Add API documentation (like WSDL schema)
• Describes the Service/request/response/models
• + add description for others to understand
• In a standardized way = according to Swagger Spec.
• Using a standardized structure, datatype names, references to
models, …
@johannes_fiala#Devoxx #Swagger
Enhance REST APIs
Benefits
• Makes the payload predictable
• Allows to use tools using the Swagger-standard
• Use Swagger-UI for exploring the API
• Generate client code with Swagger-Codegen
• Get Code completion for 20+ programming languages
• Ship SDKs in target languages
• Get correct datatypes in client code
• Get Enum support
• Get Compile-time checking of consistency
@johannes_fiala#Devoxx #Swagger
How to enhance REST APIs?
• Ask API provider to provide Swagger apidocs
• If using Spring: Springfox-libraries
• If not: see Swagger-Spring integrations
• If not possible:
• Create Swagger apidocs on your own
• Demo Today: Facebook Graph API
• Other REST-API‘s you‘d like to have enhanced?
• Google Maps API?
• ???
@johannes_fiala#Devoxx #Swagger
In the next few minutes you‘ll learn
…
• Introduction to Springfox/Swagger-Codegen
• Basic overview of Facebook Graph API
• Step-by-step Demo of using Swagger-Codegen to extract
Metadata & add them to the model
• Extract standard apidocs for Facebook
• Learn about using Swagger-Codegen
• Support of Bean Validation API: add
@NotNull/@Min/@Max by adding your own
BuilderPlugins
@johannes_fiala#Devoxx #Swagger
Technology stack
• Spring
• Spring Boot for fast start
• also possible: Spring REST/MVC
• Springfox
• For generating the api-docs
• Swagger UI
• For accessing the api using a browser
• Swagger Codegen commandline
• For generating client code stubs
@johannes_fiala#Devoxx #Swagger
Big Picture
Your REST-API
Springfox
/v2/api-docs/
Swagger-UI
/swagger/index.html
Swagger-
Codegen
Client-Code
Java, PHP, C#, Ruby, nodejs,
Objective-C, …
@johannes_fiala#Devoxx #Swagger
Springfox
• Provide complete api-docs for every @RESTController
• Services
• Supported Verbs (GET/POST/…)
• Request parameters/body
• Response codes + body
• Many customization options (hide attributes, custom data
types, …)
@johannes_fiala#Devoxx #Swagger
Swagger Codegen
• Client code stub generator (commandline)
• Generates completely customizable client stubs
• Supported languages:
• Java, C#, Dart, Flash, Groovy, JaxRS, NodeJS,
Objective-C, Perl, PHP, Python, Ruby, Scala, ….
• Ensures consistency of your client code with the API!
@johannes_fiala#Devoxx #Swagger
Swagger Codegen
• io.swagger.codegen.DefaultGenerator.generate():
• Reads api-docs in json syntax
• Scans each model
• Scans all the model properties
• Then compiles language-specific Mustache templates using a
language-specific Configuration class
• Language specific configuration:
• io.swagger.codegen.languages.*
• Mustache files: src/main/resources
@johannes_fiala#Devoxx #Swagger
Big Picture
Facebook Graph
API
Springfox
/v2/api-docs/
Swagger-
Codegen
Client-Code
Facebook Proxy
REST Service
generates (2)
calls (3)
Read field metadata (1)
@johannes_fiala#Devoxx #Swagger
Facebook Graph API
• Basic docs:
https://developers.facebook.com/docs/graph-
api/overview
• Graph API Explorer:
https://developers.facebook.com/tools/explorer
• Nice for basic testing
• Retrieve your access token
@johannes_fiala#Devoxx #Swagger
Extract metadata from the Facebook
Graph API
• Facebook Graph API url:
https://graph.facebook.com/v2.5/microsoft?access_token
=... &fields=name,about,mission
• Get field metadata: add parameter „&metadata=1“
@johannes_fiala#Devoxx #Swagger
Demo
• Demo of Facebook Graph API
@johannes_fiala#Devoxx #Swagger
Extract metadata from the Facebook
Graph API
• Target: Provide Swagger apidocs for Facebook API
• Read metadata
• Add description to fields
• Map field types to standard datatypes
• Add Enumerations
• Swagger Codegen has the Model data available during
processing and can be extended
• Alternative: Json transformation from metadata to
Swagger api
@johannes_fiala#Devoxx #Swagger
Preparation work
• a Facebook-Account
• Checkout/Download the demo project
https://github.com/jfiala/swagger-springfox-demo
@johannes_fiala#Devoxx #Swagger
Preparation work
• Modules of the swagger-springfox-demo:
• Swagger-codegen-2.1.3-facebook
• The customized Swagger-codegen code for Facbeook
• User-rest-service-2.2.2-facebook
• The Spring Boot REST-API application
• User-rest-service-2.2.2-facebook-client-java-codegen
• The generated client stubs
@johannes_fiala#Devoxx #Swagger
Big Picture
Facebook Graph
API
Springfox
/v2/api-docs/
Swagger-
Codegen
Client-Code
Facebook Proxy
REST Service
generates (2)
calls (3)
Read metadata (1)
@johannes_fiala#Devoxx #Swagger
Define the server proxy
• ConnectorUserFacebookController:
• Uses basic FacebookUser-model (with 2 attributes)
• No need to recode representation class
• Connects to Facebook using Spring Rest
• Try it using Swagger-UI
@johannes_fiala#Devoxx #Swagger
Demo
• Demo of Facebook server proxy
@johannes_fiala#Devoxx #Swagger
Big Picture
Facebook Graph
API
Springfox
/v2/api-docs/
Swagger-
Codegen
Client-Code
Facebook Proxy
REST Service
generates (2)
calls (3)
Read metadata (1)
@johannes_fiala#Devoxx #Swagger
Add metadata fields to Swagger-
Codegen
• Add fields listed in metadata
• Add field description
• Map FB field type to Swagger standard datatype
• Extract Enumerations out of description
• Add JSR-303 @NotNull, (@Min, @Max)
• + ???
• Add further Bean Validation Annotations (e.g. Size)?
• Further suggestions?
@johannes_fiala#Devoxx #Swagger
Add metadata fields to Swagger-
Codegen
• Important class: DefaultGenerator
• Line: Model model = definitions.get(name);
String access_token =„…";
String url = "https://graph.facebook.com/pivotalsoftware?access_token=" + access_token + "&metadata=1";
FacebookUser user = readJsonFromUrl(url);
for (FacebookField field : user.getMetadata().getFields()) {
propName = field.getName();
// add new virtual fields from Facebook to the model
virtualProperty = new StringProperty();
virtualProperty.setName(propName);
virtualProperty.setDescription(field.getDescription());
model.getProperties().put(propName, virtualProperty);
}
@johannes_fiala#Devoxx #Swagger
Add metadata fields to Swagger-
Codegen
• Map Facebook datatypes to Swagger datatypes
// Examples of data type mappings from Facebook-Datatypes to Swagger-Model-Datatypes
if ("bool".equals(field.getType())) {
virtualProperty = new BooleanProperty();
} else if ("unsigned int32".equals(field.getType())){
virtualProperty = new IntegerProperty();
} else {
virtualProperty = new StringProperty();
}
@johannes_fiala#Devoxx #Swagger
Add metadata fields to Swagger-
Codegen
• Extract Enum datatypes (e.g. attire)
• Description: "Dress code of the business. Applicable to Restaurants or Nightlife.
Can be one of Casual, Dressy or Unspecified“
StringProperty myStringProperty = (StringProperty)virtualProperty;
String myEnumValues = StringUtils.substringAfter(field.getDescription(), "Can be one of");
myEnumValues = StringUtils.replace(myEnumValues, " or ", ", ");
String[] enumValues = StringUtils.split(myEnumValues);
for (String myEnum : enumValues) {
myStringProperty._enum(myEnum );
}
@johannes_fiala#Devoxx #Swagger
Running the code generator
• io.swagger.codegen.Codegen -i
http://localhost:8080/v2/api-docs/ -l java –o ../facebook-
client-java
@johannes_fiala#Devoxx #Swagger
View the generated code
• The FacebookUser now has all fields of the Graph API!
@ApiModel(description = "")
public class FacebookUser {
/**
* Information about the Page
**/
@ApiModelProperty(value = "Information about the Page")
@JsonProperty("about")
public String getAbout() {
return about;
}
…
@johannes_fiala#Devoxx #Swagger
Demo
• Demo of Swagger-Codegen
@johannes_fiala#Devoxx #Swagger
Big Picture
Facebook Graph
API
Springfox
/v2/api-docs/
Swagger-
Codegen
Client-Code
Facebook Proxy
REST Service
generates (2)
calls (3)
Read metadata (1)
@johannes_fiala#Devoxx #Swagger
Client code:
Access Facebook directly
• Junit-Test: Facebook_Test.java
• Change basepath:
// TODO Step 1: replace basepath
api.getApiClient().setBasePath("https://graph.faceboo
k.com/v2.5/");
@johannes_fiala#Devoxx #Swagger
Adding a custom language
• See JavaFacebookClientCodegen
• Defines template-directory is JavaFacebook
• Now we can modify the Model
• Add @NotNull
• Add @Min, @Max
@johannes_fiala#Devoxx #Swagger
Running the code generator
• io.swagger.codegen.Codegen -i
http://localhost:8080/v2/api-docs/ -l java –o ../facebook-
client-java
@johannes_fiala#Devoxx #Swagger
Get Swagger apidocs
• Get Swagger apidocs
• Access FB through Proxy using Swagger-UI
• See model definitions in the browser
• Replace the model class „FacebookUser“
• Restart Spring Boot
• Inspect the updated model using the Swagger-UI
http://localhost:8080/swagger/index.html
@johannes_fiala#Devoxx #Swagger
Demo
• Demo of Facebook server proxy
with new FacebookUser-class
@johannes_fiala#Devoxx #Swagger
Wrapup
• Learned:
• You are able to add fields dynamically to a model class during
client-code-generation, add datatype-mapping and enums
• You are able to access the Facebook Graph API directly
• You are able to add custom languages
• Benefits:
• You can generate client code for every language supported by
Swagger-Codegen
• You have code completion for all model attributes!
@johannes_fiala#Devoxx #Swagger
Possible improvements
• Structures (e.g. Location) are currently not part of the
Facebook metadata and need to be created manually as
representation classes
• Some fields are only accessible with specific
permissions, but that‘s also not visible in the metadata
• See Helper-class AssembleFieldsUtil for details
• JSR-303 support needs further improvement
• @Min/@Max, @Size, …
@johannes_fiala#Devoxx #Swagger
Support for Beans Validation API
(JSR 303)
• Not yet implemented
• See Issue for discussion:
https://github.com/springfox/springfox/issues/356
• Can be done using extensions (Plugin Builders)
@johannes_fiala#Devoxx #Swagger
Support for Beans Validation API
How to add it yourself:
• Using „Plugins“ you can override/add to the behaviour of
Builders for Parameters/the Model
• Add a component implementing the Plugin-Interface,
e.g. ModelPropertyBuilderPlugin
• You get access to the processing context
• You can query for annotations there
• Examples: @NotNull, @Min/@Max
@johannes_fiala#Devoxx #Swagger
Support for Beans Validation API
Further available plugins
• Available Plugins for Model/Parameters:
• ModelBuilderPlugin
• ModelPropertyBuilderPlugin
• ParameterBuilderPlugin
@johannes_fiala#Devoxx #Swagger
Fine-Tuning Spring Boot
• Spring Boot adds /error path automatically
• Get rid of it using
new Docket(…)…
.apis(Predicates.not(RequestHandlerSelectors.basePack
age("org.springframework.boot")))
@johannes_fiala#Devoxx #Swagger
Hot Deploy using Spring Loaded
• Allows hot deploy
• for adding new methods etc.
• Add JVM parameters:
• -javaagent:/path_to_spring-loaded/springloaded-
1.2.4.RELEASE.jar -noverify
• https://github.com/spring-projects/spring-loaded
• http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-hotswapping
@johannes_fiala#Devoxx #Swagger
Links & Resources
• Swagger.io
http://swagger.io/open-source-integrations/
• Springfox
http://springfox.github.io/springfox/
@johannes_fiala#Devoxx #Swagger
Links & Resources
• Swagger UI
https://github.com/swagger-api/swagger-ui
• Swagger Codegen
https://github.com/swagger-api/swagger-codegen
• Chrome Plugin Swagger.ed
https://github.com/chefArchitect/apispots-browser-
swaggered
@johannes_fiala#Devoxx #Swagger
Thank you for your attention!
• Contact:
• johannes.fiala@fwd.at

Contenu connexe

Tendances

A Tour of Swagger for APIs
A Tour of Swagger for APIsA Tour of Swagger for APIs
A Tour of Swagger for APIsAllen Dean
 
Design Driven API Development
Design Driven API DevelopmentDesign Driven API Development
Design Driven API DevelopmentSokichi Fujita
 
Exposing Salesforce REST Services Using Swagger
Exposing Salesforce REST Services Using SwaggerExposing Salesforce REST Services Using Swagger
Exposing Salesforce REST Services Using SwaggerSalesforce Developers
 
Developing Faster with Swagger
Developing Faster with SwaggerDeveloping Faster with Swagger
Developing Faster with SwaggerTony Tam
 
Implement Web API with Swagger
Implement Web API with SwaggerImplement Web API with Swagger
Implement Web API with SwaggerJiang Wu
 
Consuming Restful APIs using Swagger v2.0
Consuming Restful APIs using Swagger v2.0Consuming Restful APIs using Swagger v2.0
Consuming Restful APIs using Swagger v2.0Pece Nikolovski
 
Quick run in with Swagger
Quick run in with SwaggerQuick run in with Swagger
Quick run in with SwaggerMesh Korea
 
Crystal clear service interfaces w/ Swagger/OpenAPI
Crystal clear service interfaces w/ Swagger/OpenAPICrystal clear service interfaces w/ Swagger/OpenAPI
Crystal clear service interfaces w/ Swagger/OpenAPIScott Triglia
 
Swagger - make your API accessible
Swagger - make your API accessibleSwagger - make your API accessible
Swagger - make your API accessibleVictor Trakhtenberg
 
Swagger 2.0: Latest and Greatest
Swagger 2.0: Latest and GreatestSwagger 2.0: Latest and Greatest
Swagger 2.0: Latest and GreatestLaunchAny
 
Streamlining API with Swagger.io
Streamlining API with Swagger.ioStreamlining API with Swagger.io
Streamlining API with Swagger.ioVictor Augusteo
 
Introducing Swagger
Introducing SwaggerIntroducing Swagger
Introducing SwaggerTony Tam
 
O365Con18 - SharePoint Framework for Administrators - Waldek Mastykarz
O365Con18 - SharePoint Framework for Administrators - Waldek MastykarzO365Con18 - SharePoint Framework for Administrators - Waldek Mastykarz
O365Con18 - SharePoint Framework for Administrators - Waldek MastykarzNCCOMMS
 
Swagger in the API Lifecycle
Swagger in the API LifecycleSwagger in the API Lifecycle
Swagger in the API LifecycleOle Lensmar
 
Introducing swagger
Introducing swaggerIntroducing swagger
Introducing swaggerAmr Ali
 
Building APIs with Node.js and Swagger
Building APIs with Node.js and SwaggerBuilding APIs with Node.js and Swagger
Building APIs with Node.js and SwaggerJeremy Whitlock
 
Designing APIs with OpenAPI Spec
Designing APIs with OpenAPI SpecDesigning APIs with OpenAPI Spec
Designing APIs with OpenAPI SpecAdam Paxton
 
API Design first with Swagger
API Design first with SwaggerAPI Design first with Swagger
API Design first with SwaggerTony Tam
 
How to build a Whatsapp clone in 2 hours
How to build a Whatsapp clone in 2 hoursHow to build a Whatsapp clone in 2 hours
How to build a Whatsapp clone in 2 hoursJane Chung
 
A guide to hiring a great developer to build your first app (redacted version)
A guide to hiring a great developer to build your first app (redacted version)A guide to hiring a great developer to build your first app (redacted version)
A guide to hiring a great developer to build your first app (redacted version)Oursky
 

Tendances (20)

A Tour of Swagger for APIs
A Tour of Swagger for APIsA Tour of Swagger for APIs
A Tour of Swagger for APIs
 
Design Driven API Development
Design Driven API DevelopmentDesign Driven API Development
Design Driven API Development
 
Exposing Salesforce REST Services Using Swagger
Exposing Salesforce REST Services Using SwaggerExposing Salesforce REST Services Using Swagger
Exposing Salesforce REST Services Using Swagger
 
Developing Faster with Swagger
Developing Faster with SwaggerDeveloping Faster with Swagger
Developing Faster with Swagger
 
Implement Web API with Swagger
Implement Web API with SwaggerImplement Web API with Swagger
Implement Web API with Swagger
 
Consuming Restful APIs using Swagger v2.0
Consuming Restful APIs using Swagger v2.0Consuming Restful APIs using Swagger v2.0
Consuming Restful APIs using Swagger v2.0
 
Quick run in with Swagger
Quick run in with SwaggerQuick run in with Swagger
Quick run in with Swagger
 
Crystal clear service interfaces w/ Swagger/OpenAPI
Crystal clear service interfaces w/ Swagger/OpenAPICrystal clear service interfaces w/ Swagger/OpenAPI
Crystal clear service interfaces w/ Swagger/OpenAPI
 
Swagger - make your API accessible
Swagger - make your API accessibleSwagger - make your API accessible
Swagger - make your API accessible
 
Swagger 2.0: Latest and Greatest
Swagger 2.0: Latest and GreatestSwagger 2.0: Latest and Greatest
Swagger 2.0: Latest and Greatest
 
Streamlining API with Swagger.io
Streamlining API with Swagger.ioStreamlining API with Swagger.io
Streamlining API with Swagger.io
 
Introducing Swagger
Introducing SwaggerIntroducing Swagger
Introducing Swagger
 
O365Con18 - SharePoint Framework for Administrators - Waldek Mastykarz
O365Con18 - SharePoint Framework for Administrators - Waldek MastykarzO365Con18 - SharePoint Framework for Administrators - Waldek Mastykarz
O365Con18 - SharePoint Framework for Administrators - Waldek Mastykarz
 
Swagger in the API Lifecycle
Swagger in the API LifecycleSwagger in the API Lifecycle
Swagger in the API Lifecycle
 
Introducing swagger
Introducing swaggerIntroducing swagger
Introducing swagger
 
Building APIs with Node.js and Swagger
Building APIs with Node.js and SwaggerBuilding APIs with Node.js and Swagger
Building APIs with Node.js and Swagger
 
Designing APIs with OpenAPI Spec
Designing APIs with OpenAPI SpecDesigning APIs with OpenAPI Spec
Designing APIs with OpenAPI Spec
 
API Design first with Swagger
API Design first with SwaggerAPI Design first with Swagger
API Design first with Swagger
 
How to build a Whatsapp clone in 2 hours
How to build a Whatsapp clone in 2 hoursHow to build a Whatsapp clone in 2 hours
How to build a Whatsapp clone in 2 hours
 
A guide to hiring a great developer to build your first app (redacted version)
A guide to hiring a great developer to build your first app (redacted version)A guide to hiring a great developer to build your first app (redacted version)
A guide to hiring a great developer to build your first app (redacted version)
 

Similaire à Enhance existing REST APIs (e.g. Facebook Graph API) with code completion using Swagger/Spring- Devoxx 2015

Test-Driven Documentation for your REST(ful) service
Test-Driven Documentation for your REST(ful) serviceTest-Driven Documentation for your REST(ful) service
Test-Driven Documentation for your REST(ful) serviceJeroen Reijn
 
API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)Tom Johnson
 
Spring 3 - An Introduction
Spring 3 - An IntroductionSpring 3 - An Introduction
Spring 3 - An IntroductionThorsten Kamann
 
Froyo to kit kat two years developing & maintaining deliradio
Froyo to kit kat   two years developing & maintaining deliradioFroyo to kit kat   two years developing & maintaining deliradio
Froyo to kit kat two years developing & maintaining deliradioDroidcon Berlin
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformAntonio Peric-Mazar
 
Utilizing JSF Front Ends with Microservices
Utilizing JSF Front Ends with MicroservicesUtilizing JSF Front Ends with Microservices
Utilizing JSF Front Ends with MicroservicesJosh Juneau
 
Fed London - January 2015
Fed London - January 2015Fed London - January 2015
Fed London - January 2015Phil Leggetter
 
How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016johannes_fiala
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformAntonio Peric-Mazar
 
2015-12-02 - WebCamp - Microsoft Azure Logic Apps
2015-12-02 - WebCamp - Microsoft Azure Logic Apps2015-12-02 - WebCamp - Microsoft Azure Logic Apps
2015-12-02 - WebCamp - Microsoft Azure Logic AppsSandro Pereira
 
Unlocking the power of the APEX Plugin Architecture
Unlocking the power of the APEX Plugin ArchitectureUnlocking the power of the APEX Plugin Architecture
Unlocking the power of the APEX Plugin ArchitectureMatt Nolan
 
Delivering Developer Tools at Scale
Delivering Developer Tools at ScaleDelivering Developer Tools at Scale
Delivering Developer Tools at ScaleOracle Developers
 
Xamarin.Forms Bootcamp
Xamarin.Forms BootcampXamarin.Forms Bootcamp
Xamarin.Forms BootcampMike Melusky
 
Vincent biret azure functions and flow (toronto)
Vincent biret azure functions and flow (toronto)Vincent biret azure functions and flow (toronto)
Vincent biret azure functions and flow (toronto)Vincent Biret
 
Vincent biret azure functions and flow (ottawa)
Vincent biret azure functions and flow (ottawa)Vincent biret azure functions and flow (ottawa)
Vincent biret azure functions and flow (ottawa)Vincent Biret
 
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java PlatformMicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java PlatformMike Croft
 
Swagger / Quick Start Guide
Swagger / Quick Start GuideSwagger / Quick Start Guide
Swagger / Quick Start GuideAndrii Gakhov
 
Exploring an API with Blocks
Exploring an API with BlocksExploring an API with Blocks
Exploring an API with BlocksPronovix
 

Similaire à Enhance existing REST APIs (e.g. Facebook Graph API) with code completion using Swagger/Spring- Devoxx 2015 (20)

Test-Driven Documentation for your REST(ful) service
Test-Driven Documentation for your REST(ful) serviceTest-Driven Documentation for your REST(ful) service
Test-Driven Documentation for your REST(ful) service
 
API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)
 
Spring 3 - An Introduction
Spring 3 - An IntroductionSpring 3 - An Introduction
Spring 3 - An Introduction
 
Froyo to kit kat two years developing & maintaining deliradio
Froyo to kit kat   two years developing & maintaining deliradioFroyo to kit kat   two years developing & maintaining deliradio
Froyo to kit kat two years developing & maintaining deliradio
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
Utilizing JSF Front Ends with Microservices
Utilizing JSF Front Ends with MicroservicesUtilizing JSF Front Ends with Microservices
Utilizing JSF Front Ends with Microservices
 
Fed London - January 2015
Fed London - January 2015Fed London - January 2015
Fed London - January 2015
 
How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
2015-12-02 - WebCamp - Microsoft Azure Logic Apps
2015-12-02 - WebCamp - Microsoft Azure Logic Apps2015-12-02 - WebCamp - Microsoft Azure Logic Apps
2015-12-02 - WebCamp - Microsoft Azure Logic Apps
 
Unlocking the power of the APEX Plugin Architecture
Unlocking the power of the APEX Plugin ArchitectureUnlocking the power of the APEX Plugin Architecture
Unlocking the power of the APEX Plugin Architecture
 
Delivering Developer Tools at Scale
Delivering Developer Tools at ScaleDelivering Developer Tools at Scale
Delivering Developer Tools at Scale
 
Xamarin.Forms Bootcamp
Xamarin.Forms BootcampXamarin.Forms Bootcamp
Xamarin.Forms Bootcamp
 
Vincent biret azure functions and flow (toronto)
Vincent biret azure functions and flow (toronto)Vincent biret azure functions and flow (toronto)
Vincent biret azure functions and flow (toronto)
 
Vincent biret azure functions and flow (ottawa)
Vincent biret azure functions and flow (ottawa)Vincent biret azure functions and flow (ottawa)
Vincent biret azure functions and flow (ottawa)
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
 
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java PlatformMicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
 
Swagger / Quick Start Guide
Swagger / Quick Start GuideSwagger / Quick Start Guide
Swagger / Quick Start Guide
 
Exploring an API with Blocks
Exploring an API with BlocksExploring an API with Blocks
Exploring an API with Blocks
 
All about SPFx
All about SPFxAll about SPFx
All about SPFx
 

Dernier

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Dernier (20)

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Enhance existing REST APIs (e.g. Facebook Graph API) with code completion using Swagger/Spring- Devoxx 2015

  • 1. @johannes_fiala#Devoxx #Swagger Enhance existing REST APIs (e.g. Facebook Graph API) with code completion using Swagger/Spring Johannes Fiala FWD
  • 2. @johannes_fiala#Devoxx #Swagger Enhance REST APIs • Add API documentation (like WSDL schema) • Describes the Service/request/response/models • + add description for others to understand • In a standardized way = according to Swagger Spec. • Using a standardized structure, datatype names, references to models, …
  • 3. @johannes_fiala#Devoxx #Swagger Enhance REST APIs Benefits • Makes the payload predictable • Allows to use tools using the Swagger-standard • Use Swagger-UI for exploring the API • Generate client code with Swagger-Codegen • Get Code completion for 20+ programming languages • Ship SDKs in target languages • Get correct datatypes in client code • Get Enum support • Get Compile-time checking of consistency
  • 4. @johannes_fiala#Devoxx #Swagger How to enhance REST APIs? • Ask API provider to provide Swagger apidocs • If using Spring: Springfox-libraries • If not: see Swagger-Spring integrations • If not possible: • Create Swagger apidocs on your own • Demo Today: Facebook Graph API • Other REST-API‘s you‘d like to have enhanced? • Google Maps API? • ???
  • 5. @johannes_fiala#Devoxx #Swagger In the next few minutes you‘ll learn … • Introduction to Springfox/Swagger-Codegen • Basic overview of Facebook Graph API • Step-by-step Demo of using Swagger-Codegen to extract Metadata & add them to the model • Extract standard apidocs for Facebook • Learn about using Swagger-Codegen • Support of Bean Validation API: add @NotNull/@Min/@Max by adding your own BuilderPlugins
  • 6. @johannes_fiala#Devoxx #Swagger Technology stack • Spring • Spring Boot for fast start • also possible: Spring REST/MVC • Springfox • For generating the api-docs • Swagger UI • For accessing the api using a browser • Swagger Codegen commandline • For generating client code stubs
  • 7. @johannes_fiala#Devoxx #Swagger Big Picture Your REST-API Springfox /v2/api-docs/ Swagger-UI /swagger/index.html Swagger- Codegen Client-Code Java, PHP, C#, Ruby, nodejs, Objective-C, …
  • 8. @johannes_fiala#Devoxx #Swagger Springfox • Provide complete api-docs for every @RESTController • Services • Supported Verbs (GET/POST/…) • Request parameters/body • Response codes + body • Many customization options (hide attributes, custom data types, …)
  • 9. @johannes_fiala#Devoxx #Swagger Swagger Codegen • Client code stub generator (commandline) • Generates completely customizable client stubs • Supported languages: • Java, C#, Dart, Flash, Groovy, JaxRS, NodeJS, Objective-C, Perl, PHP, Python, Ruby, Scala, …. • Ensures consistency of your client code with the API!
  • 10. @johannes_fiala#Devoxx #Swagger Swagger Codegen • io.swagger.codegen.DefaultGenerator.generate(): • Reads api-docs in json syntax • Scans each model • Scans all the model properties • Then compiles language-specific Mustache templates using a language-specific Configuration class • Language specific configuration: • io.swagger.codegen.languages.* • Mustache files: src/main/resources
  • 11. @johannes_fiala#Devoxx #Swagger Big Picture Facebook Graph API Springfox /v2/api-docs/ Swagger- Codegen Client-Code Facebook Proxy REST Service generates (2) calls (3) Read field metadata (1)
  • 12. @johannes_fiala#Devoxx #Swagger Facebook Graph API • Basic docs: https://developers.facebook.com/docs/graph- api/overview • Graph API Explorer: https://developers.facebook.com/tools/explorer • Nice for basic testing • Retrieve your access token
  • 13. @johannes_fiala#Devoxx #Swagger Extract metadata from the Facebook Graph API • Facebook Graph API url: https://graph.facebook.com/v2.5/microsoft?access_token =... &fields=name,about,mission • Get field metadata: add parameter „&metadata=1“
  • 15. @johannes_fiala#Devoxx #Swagger Extract metadata from the Facebook Graph API • Target: Provide Swagger apidocs for Facebook API • Read metadata • Add description to fields • Map field types to standard datatypes • Add Enumerations • Swagger Codegen has the Model data available during processing and can be extended • Alternative: Json transformation from metadata to Swagger api
  • 16. @johannes_fiala#Devoxx #Swagger Preparation work • a Facebook-Account • Checkout/Download the demo project https://github.com/jfiala/swagger-springfox-demo
  • 17. @johannes_fiala#Devoxx #Swagger Preparation work • Modules of the swagger-springfox-demo: • Swagger-codegen-2.1.3-facebook • The customized Swagger-codegen code for Facbeook • User-rest-service-2.2.2-facebook • The Spring Boot REST-API application • User-rest-service-2.2.2-facebook-client-java-codegen • The generated client stubs
  • 18. @johannes_fiala#Devoxx #Swagger Big Picture Facebook Graph API Springfox /v2/api-docs/ Swagger- Codegen Client-Code Facebook Proxy REST Service generates (2) calls (3) Read metadata (1)
  • 19. @johannes_fiala#Devoxx #Swagger Define the server proxy • ConnectorUserFacebookController: • Uses basic FacebookUser-model (with 2 attributes) • No need to recode representation class • Connects to Facebook using Spring Rest • Try it using Swagger-UI
  • 21. @johannes_fiala#Devoxx #Swagger Big Picture Facebook Graph API Springfox /v2/api-docs/ Swagger- Codegen Client-Code Facebook Proxy REST Service generates (2) calls (3) Read metadata (1)
  • 22. @johannes_fiala#Devoxx #Swagger Add metadata fields to Swagger- Codegen • Add fields listed in metadata • Add field description • Map FB field type to Swagger standard datatype • Extract Enumerations out of description • Add JSR-303 @NotNull, (@Min, @Max) • + ??? • Add further Bean Validation Annotations (e.g. Size)? • Further suggestions?
  • 23. @johannes_fiala#Devoxx #Swagger Add metadata fields to Swagger- Codegen • Important class: DefaultGenerator • Line: Model model = definitions.get(name); String access_token =„…"; String url = "https://graph.facebook.com/pivotalsoftware?access_token=" + access_token + "&metadata=1"; FacebookUser user = readJsonFromUrl(url); for (FacebookField field : user.getMetadata().getFields()) { propName = field.getName(); // add new virtual fields from Facebook to the model virtualProperty = new StringProperty(); virtualProperty.setName(propName); virtualProperty.setDescription(field.getDescription()); model.getProperties().put(propName, virtualProperty); }
  • 24. @johannes_fiala#Devoxx #Swagger Add metadata fields to Swagger- Codegen • Map Facebook datatypes to Swagger datatypes // Examples of data type mappings from Facebook-Datatypes to Swagger-Model-Datatypes if ("bool".equals(field.getType())) { virtualProperty = new BooleanProperty(); } else if ("unsigned int32".equals(field.getType())){ virtualProperty = new IntegerProperty(); } else { virtualProperty = new StringProperty(); }
  • 25. @johannes_fiala#Devoxx #Swagger Add metadata fields to Swagger- Codegen • Extract Enum datatypes (e.g. attire) • Description: "Dress code of the business. Applicable to Restaurants or Nightlife. Can be one of Casual, Dressy or Unspecified“ StringProperty myStringProperty = (StringProperty)virtualProperty; String myEnumValues = StringUtils.substringAfter(field.getDescription(), "Can be one of"); myEnumValues = StringUtils.replace(myEnumValues, " or ", ", "); String[] enumValues = StringUtils.split(myEnumValues); for (String myEnum : enumValues) { myStringProperty._enum(myEnum ); }
  • 26. @johannes_fiala#Devoxx #Swagger Running the code generator • io.swagger.codegen.Codegen -i http://localhost:8080/v2/api-docs/ -l java –o ../facebook- client-java
  • 27. @johannes_fiala#Devoxx #Swagger View the generated code • The FacebookUser now has all fields of the Graph API! @ApiModel(description = "") public class FacebookUser { /** * Information about the Page **/ @ApiModelProperty(value = "Information about the Page") @JsonProperty("about") public String getAbout() { return about; } …
  • 29. @johannes_fiala#Devoxx #Swagger Big Picture Facebook Graph API Springfox /v2/api-docs/ Swagger- Codegen Client-Code Facebook Proxy REST Service generates (2) calls (3) Read metadata (1)
  • 30. @johannes_fiala#Devoxx #Swagger Client code: Access Facebook directly • Junit-Test: Facebook_Test.java • Change basepath: // TODO Step 1: replace basepath api.getApiClient().setBasePath("https://graph.faceboo k.com/v2.5/");
  • 31. @johannes_fiala#Devoxx #Swagger Adding a custom language • See JavaFacebookClientCodegen • Defines template-directory is JavaFacebook • Now we can modify the Model • Add @NotNull • Add @Min, @Max
  • 32. @johannes_fiala#Devoxx #Swagger Running the code generator • io.swagger.codegen.Codegen -i http://localhost:8080/v2/api-docs/ -l java –o ../facebook- client-java
  • 33. @johannes_fiala#Devoxx #Swagger Get Swagger apidocs • Get Swagger apidocs • Access FB through Proxy using Swagger-UI • See model definitions in the browser • Replace the model class „FacebookUser“ • Restart Spring Boot • Inspect the updated model using the Swagger-UI http://localhost:8080/swagger/index.html
  • 34. @johannes_fiala#Devoxx #Swagger Demo • Demo of Facebook server proxy with new FacebookUser-class
  • 35. @johannes_fiala#Devoxx #Swagger Wrapup • Learned: • You are able to add fields dynamically to a model class during client-code-generation, add datatype-mapping and enums • You are able to access the Facebook Graph API directly • You are able to add custom languages • Benefits: • You can generate client code for every language supported by Swagger-Codegen • You have code completion for all model attributes!
  • 36. @johannes_fiala#Devoxx #Swagger Possible improvements • Structures (e.g. Location) are currently not part of the Facebook metadata and need to be created manually as representation classes • Some fields are only accessible with specific permissions, but that‘s also not visible in the metadata • See Helper-class AssembleFieldsUtil for details • JSR-303 support needs further improvement • @Min/@Max, @Size, …
  • 37. @johannes_fiala#Devoxx #Swagger Support for Beans Validation API (JSR 303) • Not yet implemented • See Issue for discussion: https://github.com/springfox/springfox/issues/356 • Can be done using extensions (Plugin Builders)
  • 38. @johannes_fiala#Devoxx #Swagger Support for Beans Validation API How to add it yourself: • Using „Plugins“ you can override/add to the behaviour of Builders for Parameters/the Model • Add a component implementing the Plugin-Interface, e.g. ModelPropertyBuilderPlugin • You get access to the processing context • You can query for annotations there • Examples: @NotNull, @Min/@Max
  • 39. @johannes_fiala#Devoxx #Swagger Support for Beans Validation API Further available plugins • Available Plugins for Model/Parameters: • ModelBuilderPlugin • ModelPropertyBuilderPlugin • ParameterBuilderPlugin
  • 40. @johannes_fiala#Devoxx #Swagger Fine-Tuning Spring Boot • Spring Boot adds /error path automatically • Get rid of it using new Docket(…)… .apis(Predicates.not(RequestHandlerSelectors.basePack age("org.springframework.boot")))
  • 41. @johannes_fiala#Devoxx #Swagger Hot Deploy using Spring Loaded • Allows hot deploy • for adding new methods etc. • Add JVM parameters: • -javaagent:/path_to_spring-loaded/springloaded- 1.2.4.RELEASE.jar -noverify • https://github.com/spring-projects/spring-loaded • http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-hotswapping
  • 42. @johannes_fiala#Devoxx #Swagger Links & Resources • Swagger.io http://swagger.io/open-source-integrations/ • Springfox http://springfox.github.io/springfox/
  • 43. @johannes_fiala#Devoxx #Swagger Links & Resources • Swagger UI https://github.com/swagger-api/swagger-ui • Swagger Codegen https://github.com/swagger-api/swagger-codegen • Chrome Plugin Swagger.ed https://github.com/chefArchitect/apispots-browser- swaggered
  • 44. @johannes_fiala#Devoxx #Swagger Thank you for your attention! • Contact: • johannes.fiala@fwd.at