SlideShare una empresa de Scribd logo
1 de 25
- documentation and testing using Swagger and Pact
Coherent REST
API design
2.
Contact Information
Frederik Mogensen
Software Developer, Cloud Team
Stibo Systems
E: frmo@stibosystems.com
L: linkedin.com/in/fmogensen
3.
Agenda
 Contract driven API design
 Provider contracts - with Swagger
 Consumer Driven contracts - with Pact
1
Contract drivenAPI design
5.
APIs in a Microservice architecture
 Unstable / changingAPIs
 No type safety between services
 No developer confidence
2
Provider contracts
- with Swagger
 “ A Provider Contract is a
description of a service offered by a
provider”
 - Steven Smith
 https://dzone.com/articles/application-pattern-consumer
7.
Swagger Example The Petstore
paths:
'/pet/’:
post:
tags:
- pet
description: Add a new pet to the store
consumes:
- application/json
produces:
- application/json
parameters:
- in: body
name: body
description:Pet object that needs to be added to the store
required:true
schema:
$ref: '#/definitions/Pet‘
responses:
'405':
description:Invalid input
'200':
description:successful operation
'/pet/{petId}':
get:
tags:
- pet
summary:Find pet by ID
produces:
- application/json
parameters:
- name: petId
in: path
description:ID of pet to return
required:true
type: integer
responses:
'200':
description:successful operation
schema:
$ref: '#/definitions/Pet'
'404':
description:Pet not found
security:
- api_key: []
8.
Why define service endpoints?
 API that are JSON first
 Documentation and clarity
 Server / Client code generation
9.
Iterative API first development
Update
Swagger
Definition
Generate
Endpoints
Implement
functionality
Test and
validate API
New demands
for API
10.
Demo using Swagger and Postman
3
Consumer-Driven contracts
- with Pact
 “ A Consumer Driven Contract is a
description of how a provider satisfies an
aggregate of Consumer Contracts ”
 - Steven Smith
 https://dzone.com/articles/application-pattern-consumer
12.
Integration test in a Microservice architecture
Characteristic
 Slow
 Easy to break
 Hard to fix
 Scales BADLY
 Lots of infrastructure
 Lots of set up
 False negatives
Infrastructure
 Startup all services
 Populate Databases
 Mock away external
services
http://www.slideshare.net/bethesque/pact-44565612
13.
Pact tests
Characteristic
 Fast
 Stable
 Easy to debug
 Reliable
 No extra infrastructure
 Low setup
 Scales linearly
Contracts for only the needed stuff
Consumer-driven contracts describes the complete set of functionality
demanded by the current set of consumers.
http://www.slideshare.net/bethesque/pact-44565612
14.
Pacts – The basics
Consumer Provider
Request
Response
http://www.slideshare.net/bethesque/pact-44565612
15.
Pacts – The basics
Consumer Provider
Request
Response
Request
Response
Pact
Consumer
Provider
http://www.slideshare.net/bethesque/pact-44565612
16.
Pact Example
Pact Broker
Mapping
Pact
Frontend
Mapping
Product
Pact
Mapping
Product
Login
Pact
Frontend
Login
Datastandard
Pact
Mapping
Datastandard
User
Pact
Login
User
Pact
iPhone
Login
17.
Pact Broker
Mapping
Pact
Frontend
Mapping
Product
Pact
Mapping
Product
Login
Pact
Frontend
Login
Datastandard
Pact
Mapping
Datastandard
User
Pact
Login
User
Pact
iPhone
Login
Pact Example
Consumer publishes
pact on build
Provider gets all pacts
from broker - on test
18.
Defining a Pact
@Pact(provider = "Datastandard", consumer = "Mapping")
public PactFragment createFragment(PactDslWithProvider builder) {
return builder
.given("datastandard-default")
.uponReceiving("A request for category with id=1 in specific datastandard")
.path("/dataStandards/dataId/categories/1")
.method("GET")
.willRespondWith()
.status(200)
.body( "{" +
""id": "1"," +
""name": "Toys"" +
"}" )
.toFragment();
}
Pact
Consumer
Provider
http://www.slideshare.net/bethesque/pact-44565612
19.
Pact example
{
"consumer": { "name": "Mapping" },
"provider": { "name": "Datastandard" },
"interactions": [
{
"producer_state": "datastandard-default",
"description": "A request for category with id=1 in specific datastandard",
"request": {
"method": "get",
"path": "/dataStandards/dataId/categories/1"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"id": "1",
"name": "Toys"
}
}
}
],
"metadata": {
"pactSpecificationVersion": "1.0.0"
}
}
Pact
Consumer
Provider
20.
Validating Pact on Consumer side
@Rule
public PactProviderRule rule = new PactProviderRule("Datastandard","localhost",“1234",this);
@Test
@PactVerification("Datastandard")
public void runTest() {
// Path variables
String datastandardId = "dataId";
String categoryId = "1";
DatastandardService datastandardService = new DatastandardService("http://localhost:1234");
Category category = datastandardService.getCategory(datastandardId, categoryId);
Category expectedCategory =
new Category().withId("1").withName("Toys");
Assert.assertEquals(expectedCategory, category);
}
Consumer
Request
Response
Pact
Consumer
Provider
http://www.slideshare.net/bethesque/pact-44565612
21.
Validating Pact on Provider side
@RunWith(PactRunner.class)
@SpringApplicationConfiguration(classes = LeapDataStandardApplication.class)
@ContextConfiguration(classes = TestAppConfig.class)
@PactBroker(BrokerProtocol = "http", BrokerHost = "docker-machine",
BrokerPort = "80", ProviderName = "Datastandard")
public class DatastandardControllerTest {
@Autowired
private DataStandardController apiController;
private DataStandardDelegateController delegateController =
mock(DataStandardDelegateController.class, Mockito.RETURNS_SMART_NULLS);
@Before
public void setUp() throws Exception {
ReflectionTestUtils.setField(apiController, "delegate", delegateController);
}
@ProviderState(value = "datastandard-default", deferredResponseInMillis = 0)
public DataStandardController shouldResponseCorrectForDefaultDataSet() {
when(delegateController.getStandardCategory( eq("dataId"), eq("1") ))
.thenReturn(new ResponseEntity<>(
new Category().withId("1").withName("Toys"), HttpStatus.OK));
return apiController;
}
}
Provider
Request
Response
Pact
Consumer
Provider
http://www.slideshare.net/bethesque/pact-44565612
22.
Problems that can be detected with Pact
 Change of the endpoint URL
 Change in the expected parameters
 Change in the response payload
23.
What is it not good for?
 Performance and load testing.
 Functional testing of the provider
 Should be done by provider's own tests
Pact is about checking the contents and
format of requests and responses.
Questions and Comments
25.
References, documentation and more…
 github.com/realestate-com-au/pact
 martinfowler.com/articles/consumerDrivenContracts.html
 slideshare.net/bethesque/pact-44565612
 slideshare.net/evanbottcher/from-monoliths-to-microservices-at-
realestatecomau
 techblog.newsweaver.com/why-should-you-use-consumer-driven-
contracts-for-microservices-integration-tests/
 dzone.com/articles/application-pattern-consumer

Más contenido relacionado

Destacado

Apis - A Cola que todos deveriam conhecer.
Apis - A Cola que todos deveriam conhecer.Apis - A Cola que todos deveriam conhecer.
Apis - A Cola que todos deveriam conhecer.Marcelo Amaral
 
Web service testing_final.pptx
Web service testing_final.pptxWeb service testing_final.pptx
Web service testing_final.pptxvodqancr
 
Expondo APIs de back-ends legados e travados
Expondo APIs de back-ends legados e travadosExpondo APIs de back-ends legados e travados
Expondo APIs de back-ends legados e travadosFábio Rosato
 
Time to REST: testing web services
Time to REST: testing web servicesTime to REST: testing web services
Time to REST: testing web servicesIurii Kutelmakh
 
Heleen Kuipers - presentatie reinventing organisations
Heleen Kuipers - presentatie reinventing organisationsHeleen Kuipers - presentatie reinventing organisations
Heleen Kuipers - presentatie reinventing organisationsForzesNL
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationMicha Kops
 
Testing RESTful web services with REST Assured
Testing RESTful web services with REST AssuredTesting RESTful web services with REST Assured
Testing RESTful web services with REST AssuredBas Dijkstra
 
Repensando o ESB: sua arquitetura SOA, usando APIs
Repensando o ESB: sua arquitetura SOA, usando APIsRepensando o ESB: sua arquitetura SOA, usando APIs
Repensando o ESB: sua arquitetura SOA, usando APIsFábio Rosato
 
Continuous Delivery Testing @HiQ
Continuous Delivery Testing @HiQContinuous Delivery Testing @HiQ
Continuous Delivery Testing @HiQTomas Riha
 
Auto-scaled Concourse CI on AWS w/o BOSH
Auto-scaled Concourse CI on AWS w/o BOSHAuto-scaled Concourse CI on AWS w/o BOSH
Auto-scaled Concourse CI on AWS w/o BOSH佑介 九岡
 
Testing RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured frameworkTesting RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured frameworkMicha Kops
 
2015-StarWest presentation on REST-assured
2015-StarWest presentation on REST-assured2015-StarWest presentation on REST-assured
2015-StarWest presentation on REST-assuredEing Ong
 
Continuous Integration with Cloud Foundry Concourse and Docker on OpenPOWER
Continuous Integration with Cloud Foundry Concourse and Docker on OpenPOWERContinuous Integration with Cloud Foundry Concourse and Docker on OpenPOWER
Continuous Integration with Cloud Foundry Concourse and Docker on OpenPOWERIndrajit Poddar
 

Destacado (20)

Apis - A Cola que todos deveriam conhecer.
Apis - A Cola que todos deveriam conhecer.Apis - A Cola que todos deveriam conhecer.
Apis - A Cola que todos deveriam conhecer.
 
Apresentação rest api
Apresentação rest apiApresentação rest api
Apresentação rest api
 
Web service testing_final.pptx
Web service testing_final.pptxWeb service testing_final.pptx
Web service testing_final.pptx
 
Autoscalable open API testing
Autoscalable open API testingAutoscalable open API testing
Autoscalable open API testing
 
Dominando o customizer
Dominando o customizerDominando o customizer
Dominando o customizer
 
Expondo APIs de back-ends legados e travados
Expondo APIs de back-ends legados e travadosExpondo APIs de back-ends legados e travados
Expondo APIs de back-ends legados e travados
 
Time to REST: testing web services
Time to REST: testing web servicesTime to REST: testing web services
Time to REST: testing web services
 
Heleen Kuipers - presentatie reinventing organisations
Heleen Kuipers - presentatie reinventing organisationsHeleen Kuipers - presentatie reinventing organisations
Heleen Kuipers - presentatie reinventing organisations
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
 
Testing RESTful web services with REST Assured
Testing RESTful web services with REST AssuredTesting RESTful web services with REST Assured
Testing RESTful web services with REST Assured
 
Repensando o ESB: sua arquitetura SOA, usando APIs
Repensando o ESB: sua arquitetura SOA, usando APIsRepensando o ESB: sua arquitetura SOA, usando APIs
Repensando o ESB: sua arquitetura SOA, usando APIs
 
Rest assured
Rest assuredRest assured
Rest assured
 
Continuous Delivery Testing @HiQ
Continuous Delivery Testing @HiQContinuous Delivery Testing @HiQ
Continuous Delivery Testing @HiQ
 
Auto-scaled Concourse CI on AWS w/o BOSH
Auto-scaled Concourse CI on AWS w/o BOSHAuto-scaled Concourse CI on AWS w/o BOSH
Auto-scaled Concourse CI on AWS w/o BOSH
 
Testing RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured frameworkTesting RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured framework
 
2015-StarWest presentation on REST-assured
2015-StarWest presentation on REST-assured2015-StarWest presentation on REST-assured
2015-StarWest presentation on REST-assured
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
testng
testngtestng
testng
 
Continuous Integration with Cloud Foundry Concourse and Docker on OpenPOWER
Continuous Integration with Cloud Foundry Concourse and Docker on OpenPOWERContinuous Integration with Cloud Foundry Concourse and Docker on OpenPOWER
Continuous Integration with Cloud Foundry Concourse and Docker on OpenPOWER
 
Api testing
Api testingApi testing
Api testing
 

Similar a Coherent REST API design

Contract testing | Евгений Кузьмин | CODEiD
Contract testing | Евгений Кузьмин | CODEiDContract testing | Евгений Кузьмин | CODEiD
Contract testing | Евгений Кузьмин | CODEiDCODEiD PHP Community
 
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...Evgeniy Kuzmin
 
Contract testing and Pact
Contract testing and PactContract testing and Pact
Contract testing and PactSeb Rose
 
Software contracts - Global Enterprise Agile 2023.pdf
Software contracts - Global Enterprise Agile 2023.pdfSoftware contracts - Global Enterprise Agile 2023.pdf
Software contracts - Global Enterprise Agile 2023.pdfSeb Rose
 
Consumer Driven Contracts (DDD Perth 2016)
Consumer Driven Contracts (DDD Perth 2016)Consumer Driven Contracts (DDD Perth 2016)
Consumer Driven Contracts (DDD Perth 2016)Rob Crowley
 
Consumer-Driven Contract Testing
Consumer-Driven Contract TestingConsumer-Driven Contract Testing
Consumer-Driven Contract TestingPaulo Clavijo
 
Z101666 best practices for delivering hybrid cloud capability with apis
Z101666 best practices for delivering hybrid cloud capability with apisZ101666 best practices for delivering hybrid cloud capability with apis
Z101666 best practices for delivering hybrid cloud capability with apisTeodoro Cipresso
 
[WSO2Con EU 2018] Blockchain in the Business API Ecosystem - API Consumption ...
[WSO2Con EU 2018] Blockchain in the Business API Ecosystem - API Consumption ...[WSO2Con EU 2018] Blockchain in the Business API Ecosystem - API Consumption ...
[WSO2Con EU 2018] Blockchain in the Business API Ecosystem - API Consumption ...WSO2
 
Consumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice ArchitectureConsumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice ArchitectureMarcin Grzejszczak
 
Consumer driven contracts in java world
Consumer driven contracts in java worldConsumer driven contracts in java world
Consumer driven contracts in java worldYura Nosenko
 
Consumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice ArchitectureConsumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice ArchitectureVMware Tanzu
 
What API Specifications and Tools Help Engineers to Construct a High-Security...
What API Specifications and Tools Help Engineers to Construct a High-Security...What API Specifications and Tools Help Engineers to Construct a High-Security...
What API Specifications and Tools Help Engineers to Construct a High-Security...Hitachi, Ltd. OSS Solution Center.
 
Micro-service delivery - without the pitfalls
Micro-service delivery - without the pitfallsMicro-service delivery - without the pitfalls
Micro-service delivery - without the pitfallsSeb Rose
 
Vistex Contract Overview
Vistex Contract OverviewVistex Contract Overview
Vistex Contract OverviewSAPYard
 
TDD for Microservices
TDD for MicroservicesTDD for Microservices
TDD for MicroservicesVMware Tanzu
 
Contract Testing
Contract TestingContract Testing
Contract Testingkloia
 
Contract testing - Sealights 2022.pdf
Contract testing - Sealights 2022.pdfContract testing - Sealights 2022.pdf
Contract testing - Sealights 2022.pdfSeb Rose
 
AppGate Getting Started Resources for Telarus Partners
AppGate Getting Started Resources for Telarus PartnersAppGate Getting Started Resources for Telarus Partners
AppGate Getting Started Resources for Telarus PartnersSaraPia5
 

Similar a Coherent REST API design (20)

Contract testing | Евгений Кузьмин | CODEiD
Contract testing | Евгений Кузьмин | CODEiDContract testing | Евгений Кузьмин | CODEiD
Contract testing | Евгений Кузьмин | CODEiD
 
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
 
Contract testing and Pact
Contract testing and PactContract testing and Pact
Contract testing and Pact
 
Software contracts - Global Enterprise Agile 2023.pdf
Software contracts - Global Enterprise Agile 2023.pdfSoftware contracts - Global Enterprise Agile 2023.pdf
Software contracts - Global Enterprise Agile 2023.pdf
 
Consumer Driven Contracts (DDD Perth 2016)
Consumer Driven Contracts (DDD Perth 2016)Consumer Driven Contracts (DDD Perth 2016)
Consumer Driven Contracts (DDD Perth 2016)
 
Consumer-Driven Contract Testing
Consumer-Driven Contract TestingConsumer-Driven Contract Testing
Consumer-Driven Contract Testing
 
Z101666 best practices for delivering hybrid cloud capability with apis
Z101666 best practices for delivering hybrid cloud capability with apisZ101666 best practices for delivering hybrid cloud capability with apis
Z101666 best practices for delivering hybrid cloud capability with apis
 
[WSO2Con EU 2018] Blockchain in the Business API Ecosystem - API Consumption ...
[WSO2Con EU 2018] Blockchain in the Business API Ecosystem - API Consumption ...[WSO2Con EU 2018] Blockchain in the Business API Ecosystem - API Consumption ...
[WSO2Con EU 2018] Blockchain in the Business API Ecosystem - API Consumption ...
 
Consumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice ArchitectureConsumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice Architecture
 
Consumer driven contracts in java world
Consumer driven contracts in java worldConsumer driven contracts in java world
Consumer driven contracts in java world
 
SVQdotNET: Building APIs with OpenApi
SVQdotNET: Building APIs with OpenApiSVQdotNET: Building APIs with OpenApi
SVQdotNET: Building APIs with OpenApi
 
Consumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice ArchitectureConsumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice Architecture
 
What API Specifications and Tools Help Engineers to Construct a High-Security...
What API Specifications and Tools Help Engineers to Construct a High-Security...What API Specifications and Tools Help Engineers to Construct a High-Security...
What API Specifications and Tools Help Engineers to Construct a High-Security...
 
Micro-service delivery - without the pitfalls
Micro-service delivery - without the pitfallsMicro-service delivery - without the pitfalls
Micro-service delivery - without the pitfalls
 
Vistex Contract Overview
Vistex Contract OverviewVistex Contract Overview
Vistex Contract Overview
 
TDD for Microservices
TDD for MicroservicesTDD for Microservices
TDD for Microservices
 
Contract Testing
Contract TestingContract Testing
Contract Testing
 
Mastering the api hell
Mastering the api hellMastering the api hell
Mastering the api hell
 
Contract testing - Sealights 2022.pdf
Contract testing - Sealights 2022.pdfContract testing - Sealights 2022.pdf
Contract testing - Sealights 2022.pdf
 
AppGate Getting Started Resources for Telarus Partners
AppGate Getting Started Resources for Telarus PartnersAppGate Getting Started Resources for Telarus Partners
AppGate Getting Started Resources for Telarus Partners
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Coherent REST API design

  • 1. - documentation and testing using Swagger and Pact Coherent REST API design
  • 2. 2. Contact Information Frederik Mogensen Software Developer, Cloud Team Stibo Systems E: frmo@stibosystems.com L: linkedin.com/in/fmogensen
  • 3. 3. Agenda  Contract driven API design  Provider contracts - with Swagger  Consumer Driven contracts - with Pact
  • 5. 5. APIs in a Microservice architecture  Unstable / changingAPIs  No type safety between services  No developer confidence
  • 6. 2 Provider contracts - with Swagger  “ A Provider Contract is a description of a service offered by a provider”  - Steven Smith  https://dzone.com/articles/application-pattern-consumer
  • 7. 7. Swagger Example The Petstore paths: '/pet/’: post: tags: - pet description: Add a new pet to the store consumes: - application/json produces: - application/json parameters: - in: body name: body description:Pet object that needs to be added to the store required:true schema: $ref: '#/definitions/Pet‘ responses: '405': description:Invalid input '200': description:successful operation '/pet/{petId}': get: tags: - pet summary:Find pet by ID produces: - application/json parameters: - name: petId in: path description:ID of pet to return required:true type: integer responses: '200': description:successful operation schema: $ref: '#/definitions/Pet' '404': description:Pet not found security: - api_key: []
  • 8. 8. Why define service endpoints?  API that are JSON first  Documentation and clarity  Server / Client code generation
  • 9. 9. Iterative API first development Update Swagger Definition Generate Endpoints Implement functionality Test and validate API New demands for API
  • 10. 10. Demo using Swagger and Postman
  • 11. 3 Consumer-Driven contracts - with Pact  “ A Consumer Driven Contract is a description of how a provider satisfies an aggregate of Consumer Contracts ”  - Steven Smith  https://dzone.com/articles/application-pattern-consumer
  • 12. 12. Integration test in a Microservice architecture Characteristic  Slow  Easy to break  Hard to fix  Scales BADLY  Lots of infrastructure  Lots of set up  False negatives Infrastructure  Startup all services  Populate Databases  Mock away external services http://www.slideshare.net/bethesque/pact-44565612
  • 13. 13. Pact tests Characteristic  Fast  Stable  Easy to debug  Reliable  No extra infrastructure  Low setup  Scales linearly Contracts for only the needed stuff Consumer-driven contracts describes the complete set of functionality demanded by the current set of consumers. http://www.slideshare.net/bethesque/pact-44565612
  • 14. 14. Pacts – The basics Consumer Provider Request Response http://www.slideshare.net/bethesque/pact-44565612
  • 15. 15. Pacts – The basics Consumer Provider Request Response Request Response Pact Consumer Provider http://www.slideshare.net/bethesque/pact-44565612
  • 18. 18. Defining a Pact @Pact(provider = "Datastandard", consumer = "Mapping") public PactFragment createFragment(PactDslWithProvider builder) { return builder .given("datastandard-default") .uponReceiving("A request for category with id=1 in specific datastandard") .path("/dataStandards/dataId/categories/1") .method("GET") .willRespondWith() .status(200) .body( "{" + ""id": "1"," + ""name": "Toys"" + "}" ) .toFragment(); } Pact Consumer Provider http://www.slideshare.net/bethesque/pact-44565612
  • 19. 19. Pact example { "consumer": { "name": "Mapping" }, "provider": { "name": "Datastandard" }, "interactions": [ { "producer_state": "datastandard-default", "description": "A request for category with id=1 in specific datastandard", "request": { "method": "get", "path": "/dataStandards/dataId/categories/1" }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": { "id": "1", "name": "Toys" } } } ], "metadata": { "pactSpecificationVersion": "1.0.0" } } Pact Consumer Provider
  • 20. 20. Validating Pact on Consumer side @Rule public PactProviderRule rule = new PactProviderRule("Datastandard","localhost",“1234",this); @Test @PactVerification("Datastandard") public void runTest() { // Path variables String datastandardId = "dataId"; String categoryId = "1"; DatastandardService datastandardService = new DatastandardService("http://localhost:1234"); Category category = datastandardService.getCategory(datastandardId, categoryId); Category expectedCategory = new Category().withId("1").withName("Toys"); Assert.assertEquals(expectedCategory, category); } Consumer Request Response Pact Consumer Provider http://www.slideshare.net/bethesque/pact-44565612
  • 21. 21. Validating Pact on Provider side @RunWith(PactRunner.class) @SpringApplicationConfiguration(classes = LeapDataStandardApplication.class) @ContextConfiguration(classes = TestAppConfig.class) @PactBroker(BrokerProtocol = "http", BrokerHost = "docker-machine", BrokerPort = "80", ProviderName = "Datastandard") public class DatastandardControllerTest { @Autowired private DataStandardController apiController; private DataStandardDelegateController delegateController = mock(DataStandardDelegateController.class, Mockito.RETURNS_SMART_NULLS); @Before public void setUp() throws Exception { ReflectionTestUtils.setField(apiController, "delegate", delegateController); } @ProviderState(value = "datastandard-default", deferredResponseInMillis = 0) public DataStandardController shouldResponseCorrectForDefaultDataSet() { when(delegateController.getStandardCategory( eq("dataId"), eq("1") )) .thenReturn(new ResponseEntity<>( new Category().withId("1").withName("Toys"), HttpStatus.OK)); return apiController; } } Provider Request Response Pact Consumer Provider http://www.slideshare.net/bethesque/pact-44565612
  • 22. 22. Problems that can be detected with Pact  Change of the endpoint URL  Change in the expected parameters  Change in the response payload
  • 23. 23. What is it not good for?  Performance and load testing.  Functional testing of the provider  Should be done by provider's own tests Pact is about checking the contents and format of requests and responses.
  • 25. 25. References, documentation and more…  github.com/realestate-com-au/pact  martinfowler.com/articles/consumerDrivenContracts.html  slideshare.net/bethesque/pact-44565612  slideshare.net/evanbottcher/from-monoliths-to-microservices-at- realestatecomau  techblog.newsweaver.com/why-should-you-use-consumer-driven- contracts-for-microservices-integration-tests/  dzone.com/articles/application-pattern-consumer

Notas del editor

  1. In this talk we look at using Swagger and Pact to handle REST API specifications and contracts. Swagger allows for a JSON first specification of the API as well as generating and discovering service controllers. This can be done coherently across multiple technology stacks. We will look into using Pact to create consumer driven contract between services in a micro service architecture to improve development confidence.
  2. Different consumers of services -> JSON / XML Ever evolving microservices we need to change the API Problem senario 1. Provider service is being updated to a new version 2. It is behaving perfectly 3. But suddenly a number of other services start behaving incorrectly
  3. JSON FIRST: Not just what ever the given framework produces at a given time CODE GEN: Server - Java - C# - C - Ruby - Node - PHP Client - Android - Java - Dart - Perl - Akka scala - Swift - Ruby
  4. http://Docker-machine/api/v1/excel/swagger-ui.html http://docker-machine/api/v1/excel/v2/api-docs
  5. 1. The consumer defines what it expects from a specific request to a service 2. The provider and the consumer agree on this contract 3. The provider continuously verifies that the contract is fulfilled
  6. E.g. renamed endpoints E.g. new mandatory fields Returns an array, instead of having an array wrapped in an object Clearly API-breaking changes. May not be obvious that a code change changes the API. - Renamed Class / Field that are later JSON serialized It may also not be clear which Consumers are affected by code changes.