SlideShare a Scribd company logo
JSON Schema: Your API’s
Secret Weapon
API Craft Boston / 2016-03-10
Pete Gamache / pete@appcues.com / @gamache
JSON Schema
Describes the structure of JSON data using a JSON-based
language
Standards-track
Simple
Great at nested objects
Generally treated as documentation
Good library support, though
Example: Event
{

"name": "button_click",

"timestamp": 1457437187,

"attributes": {

"button_id": 271828,

"page": "/"

}

}
Example JSON Schema
{

"$schema": "http://json-schema.org/draft-04/schema#",

"title": "Example Schema",

"definitions": {

"event": {

"type": "object",

"required": ["name", "timestamp"],

"properties": {

"name": {"type": "string"},

"timestamp": {"type": "integer"},

"attributes": {"type": "object"}

}

},

// ...
Example: Event Collection
{

"events": [

{

"name": "button_click",

"timestamp": 1457437187,

"attributes": {

"button_id": 271828,

"page": "/"

}

},

// ...

]

}
Example JSON Schema
{

"$schema": "http://json-schema.org/draft-04/schema#",

"title": "Example Schema",

"definitions": { // ...

"event_collection": {

"required": ["events"],

"properties": {

"events": {

"type": "array",

"items": {"ref": "#/definitions/event"}

}

}

},

// ...
It would be a shame for a
lovely, machine-readable
doc like that to be wasted
on humans...
JSON Validation with Elixir
and ExJsonSchema
iex> schema = File.read!("schema.json") |> Poison.decode!
|> ExJsonSchema.Schema.resolve



iex> event_schema = schema.schema["definitions"]["event"]



iex> ExJsonSchema.Validator.validate(schema,
event_schema, %{})

[{"Required property name was not present.", []},

{"Required property timestamp was not present.", []}]



iex> ExJsonSchema.Validator.validate(schema,
event_schema, %{"name" => "hi", "timestamp" => 1})

[]
JSON Validation with Elixir
and ExJsonSchema, cont.
iex> event_collection_schema = schema.schema["definitions"]
["event_collection"]



iex> ExJsonSchema.Validator.validate(schema, event_collection_schema,

...> %{"events" => [

...> %{"name" => "event 1", "attributes" => %{"awesome" => true}},

...> %{"name" => "event 2", "timestamp" => "whenever"},

...> %{"name" => "event 3", "timestamp" => 1234567890}

...> ]})

[{"Required property timestamp was not present.", ["events", 0]},

{"Expected "whenever" to be a valid ISO 8601 date-time.",

["events", 1, "timestamp"]}]
Use Case 1: Input Validation
Writing data validators is a pain, especially for anything
complex
Not only do we have to validate input, we need to
generate coherent error messages
Lots of opportunity to reinvent the wheel, but let's not
API Input Validation with
Elixir and ExJsonSchema
defmodule MyApp.EventsController do

use MyApp.Web, :controller

plug :validate_params



defp validate_params(conn, _params) do

case JsonSchema.validate(conn.params, :event_collection) do

[] ->

conn |> assign(:event_collection, conn.params)

errors ->

json_errors = errors |> JsonSchema.errors_to_json

conn |> put_status(422) |> json(%{errors: json_errors}) |> halt

end

end



def save_events(conn, params) do

event_collection = conn.assigns[:event_collection]

# ... do something here

conn |> put_status(202) |> json(%{ok: true})

end

end
Use Case 2: Output Validation
Pointing to the JSON Schema in API docs is great for
humans
Performing JSON Schema validation in API tests
ensures your docs aren't lying*. This is also great for
humans

* at least not about output data structure format
API Output Validation with
Elixir and ExJsonSchema
defmodule MyApp.EventsControllerTest do

use Plug.Test



test "it returns well-formed event collection" do

resp = conn(:post, "url goes here", %{params: ...})

|> MyApp.Router.call(MyApp.Router.init([]))

resp_object = resp.resp_body |> Poison.decode!

assert([] ==

JsonSchema.validate(resp_object, :event_collection))

end



# ... more tests here

end
References
http://json-schema.org/
JSON Pointer -- https://tools.ietf.org/html/rfc6901
https://github.com/jonasschmidt/ex_json_schema
https://engineering.appcues.com/2016/01/20/ex-json-
schema.html
http://www.slideshare.net/petegamache/
jsonschema20160310
Questions?
Love APIs? Appcues is hiring!
APIs in Elixir and ES6/AWS Lambda/API Gateway
Frontend in ES6/Redux/React
http://tinyurl.com/appcues-full-stack

More Related Content

What's hot

Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
t k
 
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Codemotion
 
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
Ben Teese
 
Creating sub zero dashboard plugin for apex with google
Creating sub zero dashboard plugin for apex with googleCreating sub zero dashboard plugin for apex with google
Creating sub zero dashboard plugin for apex with google
Roel Hartman
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Codemotion
 
Tweaking the interactive grid
Tweaking the interactive gridTweaking the interactive grid
Tweaking the interactive grid
Roel Hartman
 
Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web Apps
Mark
 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB API
Waldyr Felix
 
Iterators & generators: practical uses in memory management
Iterators & generators: practical uses in memory managementIterators & generators: practical uses in memory management
Iterators & generators: practical uses in memory management
Adrian Cardenas
 
Consuming Web Services with Swift and Rx
Consuming Web Services with Swift and RxConsuming Web Services with Swift and Rx
Consuming Web Services with Swift and Rx
Guillermo Gonzalez
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
Mark
 
Cakephp2study tips集
Cakephp2study tips集Cakephp2study tips集
Cakephp2study tips集
Kohji Tanaka
 
Going Serverless
Going ServerlessGoing Serverless
Going Serverless
Mattias Severson
 
Scala.js: Next generation front end development in Scala
Scala.js:  Next generation front end development in ScalaScala.js:  Next generation front end development in Scala
Scala.js: Next generation front end development in Scala
Otto Chrons
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive Apps
Jorge Ortiz
 
Vaadin+Scala
Vaadin+ScalaVaadin+Scala
Vaadin+Scala
Vasil Remeniuk
 
A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...
Codemotion
 
Programming Google apps with the G Suite APIs
Programming Google apps with the G Suite APIsProgramming Google apps with the G Suite APIs
Programming Google apps with the G Suite APIs
DevFest DC
 
Insert latest articles on blogger
Insert latest articles on bloggerInsert latest articles on blogger
Insert latest articles on blogger
Stefano Vinci
 
Introduction to Ember
Introduction to EmberIntroduction to Ember
Introduction to Ember
SmartLogic
 

What's hot (20)

Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
 
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
 
Creating sub zero dashboard plugin for apex with google
Creating sub zero dashboard plugin for apex with googleCreating sub zero dashboard plugin for apex with google
Creating sub zero dashboard plugin for apex with google
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
 
Tweaking the interactive grid
Tweaking the interactive gridTweaking the interactive grid
Tweaking the interactive grid
 
Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web Apps
 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB API
 
Iterators & generators: practical uses in memory management
Iterators & generators: practical uses in memory managementIterators & generators: practical uses in memory management
Iterators & generators: practical uses in memory management
 
Consuming Web Services with Swift and Rx
Consuming Web Services with Swift and RxConsuming Web Services with Swift and Rx
Consuming Web Services with Swift and Rx
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
 
Cakephp2study tips集
Cakephp2study tips集Cakephp2study tips集
Cakephp2study tips集
 
Going Serverless
Going ServerlessGoing Serverless
Going Serverless
 
Scala.js: Next generation front end development in Scala
Scala.js:  Next generation front end development in ScalaScala.js:  Next generation front end development in Scala
Scala.js: Next generation front end development in Scala
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive Apps
 
Vaadin+Scala
Vaadin+ScalaVaadin+Scala
Vaadin+Scala
 
A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...
 
Programming Google apps with the G Suite APIs
Programming Google apps with the G Suite APIsProgramming Google apps with the G Suite APIs
Programming Google apps with the G Suite APIs
 
Insert latest articles on blogger
Insert latest articles on bloggerInsert latest articles on blogger
Insert latest articles on blogger
 
Introduction to Ember
Introduction to EmberIntroduction to Ember
Introduction to Ember
 

Similar to JSON Schema: Your API's Secret Weapon

Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
Paco de la Cruz
 
[JCConf 2020] 用 Kotlin 跨入 Serverless 世代
[JCConf 2020] 用 Kotlin 跨入 Serverless 世代[JCConf 2020] 用 Kotlin 跨入 Serverless 世代
[JCConf 2020] 用 Kotlin 跨入 Serverless 世代
Shengyou Fan
 
infrastructure as code
infrastructure as codeinfrastructure as code
infrastructure as code
Amazon Web Services
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Ismael Celis
 
AWS May Webinar Series - Deep Dive: Infrastructure as Code
AWS May Webinar Series - Deep Dive: Infrastructure as CodeAWS May Webinar Series - Deep Dive: Infrastructure as Code
AWS May Webinar Series - Deep Dive: Infrastructure as Code
Amazon Web Services
 
DevOps on AWS: Deep Dive on Infrastructure as Code - Toronto
DevOps on AWS: Deep Dive on Infrastructure as Code - TorontoDevOps on AWS: Deep Dive on Infrastructure as Code - Toronto
DevOps on AWS: Deep Dive on Infrastructure as Code - Toronto
Amazon Web Services
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)
Paco de la Cruz
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant TrainingAidIQ
 
Deep Dive: Infrastructure as Code
Deep Dive: Infrastructure as CodeDeep Dive: Infrastructure as Code
Deep Dive: Infrastructure as Code
Amazon Web Services
 
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, EverAltitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Fastly
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Client-side Rendering with AngularJS
Client-side Rendering with AngularJSClient-side Rendering with AngularJS
Client-side Rendering with AngularJS
David Lapsley
 
Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonML
Riza Fahmi
 
Introduction to ReasonML
Introduction to ReasonMLIntroduction to ReasonML
Introduction to ReasonML
Riza Fahmi
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
Boris Dinkevich
 
Deep Dive: Infrastructure as Code
Deep Dive: Infrastructure as CodeDeep Dive: Infrastructure as Code
Deep Dive: Infrastructure as Code
Amazon Web Services
 
Deep Dive: Infrastructure as Code
Deep Dive: Infrastructure as CodeDeep Dive: Infrastructure as Code
Deep Dive: Infrastructure as Code
Amazon Web Services
 
Server Side Events
Server Side EventsServer Side Events
Server Side Events
thepilif
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
Ben Lesh
 

Similar to JSON Schema: Your API's Secret Weapon (20)

Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
 
[JCConf 2020] 用 Kotlin 跨入 Serverless 世代
[JCConf 2020] 用 Kotlin 跨入 Serverless 世代[JCConf 2020] 用 Kotlin 跨入 Serverless 世代
[JCConf 2020] 用 Kotlin 跨入 Serverless 世代
 
infrastructure as code
infrastructure as codeinfrastructure as code
infrastructure as code
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010
 
AWS May Webinar Series - Deep Dive: Infrastructure as Code
AWS May Webinar Series - Deep Dive: Infrastructure as CodeAWS May Webinar Series - Deep Dive: Infrastructure as Code
AWS May Webinar Series - Deep Dive: Infrastructure as Code
 
DevOps on AWS: Deep Dive on Infrastructure as Code - Toronto
DevOps on AWS: Deep Dive on Infrastructure as Code - TorontoDevOps on AWS: Deep Dive on Infrastructure as Code - Toronto
DevOps on AWS: Deep Dive on Infrastructure as Code - Toronto
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
 
Deep Dive: Infrastructure as Code
Deep Dive: Infrastructure as CodeDeep Dive: Infrastructure as Code
Deep Dive: Infrastructure as Code
 
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, EverAltitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Client-side Rendering with AngularJS
Client-side Rendering with AngularJSClient-side Rendering with AngularJS
Client-side Rendering with AngularJS
 
Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonML
 
Introduction to ReasonML
Introduction to ReasonMLIntroduction to ReasonML
Introduction to ReasonML
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
 
Deep Dive: Infrastructure as Code
Deep Dive: Infrastructure as CodeDeep Dive: Infrastructure as Code
Deep Dive: Infrastructure as Code
 
Deep Dive: Infrastructure as Code
Deep Dive: Infrastructure as CodeDeep Dive: Infrastructure as Code
Deep Dive: Infrastructure as Code
 
Server Side Events
Server Side EventsServer Side Events
Server Side Events
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 

Recently uploaded

Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 

Recently uploaded (20)

Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 

JSON Schema: Your API's Secret Weapon

  • 1. JSON Schema: Your API’s Secret Weapon API Craft Boston / 2016-03-10 Pete Gamache / pete@appcues.com / @gamache
  • 2. JSON Schema Describes the structure of JSON data using a JSON-based language Standards-track Simple Great at nested objects Generally treated as documentation Good library support, though
  • 3. Example: Event {
 "name": "button_click",
 "timestamp": 1457437187,
 "attributes": {
 "button_id": 271828,
 "page": "/"
 }
 }
  • 4. Example JSON Schema {
 "$schema": "http://json-schema.org/draft-04/schema#",
 "title": "Example Schema",
 "definitions": {
 "event": {
 "type": "object",
 "required": ["name", "timestamp"],
 "properties": {
 "name": {"type": "string"},
 "timestamp": {"type": "integer"},
 "attributes": {"type": "object"}
 }
 },
 // ...
  • 5. Example: Event Collection {
 "events": [
 {
 "name": "button_click",
 "timestamp": 1457437187,
 "attributes": {
 "button_id": 271828,
 "page": "/"
 }
 },
 // ...
 ]
 }
  • 6. Example JSON Schema {
 "$schema": "http://json-schema.org/draft-04/schema#",
 "title": "Example Schema",
 "definitions": { // ...
 "event_collection": {
 "required": ["events"],
 "properties": {
 "events": {
 "type": "array",
 "items": {"ref": "#/definitions/event"}
 }
 }
 },
 // ...
  • 7. It would be a shame for a lovely, machine-readable doc like that to be wasted on humans...
  • 8. JSON Validation with Elixir and ExJsonSchema iex> schema = File.read!("schema.json") |> Poison.decode! |> ExJsonSchema.Schema.resolve
 
 iex> event_schema = schema.schema["definitions"]["event"]
 
 iex> ExJsonSchema.Validator.validate(schema, event_schema, %{})
 [{"Required property name was not present.", []},
 {"Required property timestamp was not present.", []}]
 
 iex> ExJsonSchema.Validator.validate(schema, event_schema, %{"name" => "hi", "timestamp" => 1})
 []
  • 9. JSON Validation with Elixir and ExJsonSchema, cont. iex> event_collection_schema = schema.schema["definitions"] ["event_collection"]
 
 iex> ExJsonSchema.Validator.validate(schema, event_collection_schema,
 ...> %{"events" => [
 ...> %{"name" => "event 1", "attributes" => %{"awesome" => true}},
 ...> %{"name" => "event 2", "timestamp" => "whenever"},
 ...> %{"name" => "event 3", "timestamp" => 1234567890}
 ...> ]})
 [{"Required property timestamp was not present.", ["events", 0]},
 {"Expected "whenever" to be a valid ISO 8601 date-time.",
 ["events", 1, "timestamp"]}]
  • 10. Use Case 1: Input Validation Writing data validators is a pain, especially for anything complex Not only do we have to validate input, we need to generate coherent error messages Lots of opportunity to reinvent the wheel, but let's not
  • 11. API Input Validation with Elixir and ExJsonSchema defmodule MyApp.EventsController do
 use MyApp.Web, :controller
 plug :validate_params
 
 defp validate_params(conn, _params) do
 case JsonSchema.validate(conn.params, :event_collection) do
 [] ->
 conn |> assign(:event_collection, conn.params)
 errors ->
 json_errors = errors |> JsonSchema.errors_to_json
 conn |> put_status(422) |> json(%{errors: json_errors}) |> halt
 end
 end
 
 def save_events(conn, params) do
 event_collection = conn.assigns[:event_collection]
 # ... do something here
 conn |> put_status(202) |> json(%{ok: true})
 end
 end
  • 12. Use Case 2: Output Validation Pointing to the JSON Schema in API docs is great for humans Performing JSON Schema validation in API tests ensures your docs aren't lying*. This is also great for humans
 * at least not about output data structure format
  • 13. API Output Validation with Elixir and ExJsonSchema defmodule MyApp.EventsControllerTest do
 use Plug.Test
 
 test "it returns well-formed event collection" do
 resp = conn(:post, "url goes here", %{params: ...})
 |> MyApp.Router.call(MyApp.Router.init([]))
 resp_object = resp.resp_body |> Poison.decode!
 assert([] ==
 JsonSchema.validate(resp_object, :event_collection))
 end
 
 # ... more tests here
 end
  • 14. References http://json-schema.org/ JSON Pointer -- https://tools.ietf.org/html/rfc6901 https://github.com/jonasschmidt/ex_json_schema https://engineering.appcues.com/2016/01/20/ex-json- schema.html http://www.slideshare.net/petegamache/ jsonschema20160310
  • 16. Love APIs? Appcues is hiring! APIs in Elixir and ES6/AWS Lambda/API Gateway Frontend in ES6/Redux/React http://tinyurl.com/appcues-full-stack