Beyond Documentation with OpenAPI

A presentation at PHP CE in October 2018 in Prague, Czechia by Boyan Yordanov

Slide 1

Slide 1

BEYOND DOCUMENTATION WITH OpenAPI

Slide 2

Slide 2

GET /SPEAKERS/BOYAN Boyan Yordanov @specter_bg PHP Varna and VarnaJS organizer VarnaLab member Developer@ShtrakBG

Slide 3

Slide 3

WHO LIKES WRITING DOCUMENTATION?

Slide 4

Slide 4

DOCUMENTATION THAT IS: “too long to read” “totally useless” “not updated”

Slide 5

Slide 5

JUST BORING

Slide 6

Slide 6

API SPECIFICATIONS machine readable easy to write more than documentation

Slide 7

Slide 7

I still have to write it, though. - me

Slide 8

Slide 8

I can do so many cool things with this de nition. - also me (a couple of months later)

Slide 9

Slide 9

WHY BOTHER WITH AN API SPECIFICATION?

Slide 10

Slide 10

HAVE YOU BEEN THIS PERSON? http://www.commitstrip.com

Slide 11

Slide 11

HOW ABOUT THIS?

Slide 12

Slide 12

OUR PROCESS HAS FAILED US

Slide 13

Slide 13

  1. LITTLE UPFRONT DESIGN WORK

Slide 14

Slide 14

  1. UNANNOUNCED OR MISCOMMUNICATED CHANGES

Slide 15

Slide 15

WASTED TIME AND A LOT OF FRUSTRATION

Slide 16

Slide 16

COMMON PROBLEMS changes aren’t properly tested clients constantly wait for the API documentation and code don’t match SDKs have another opinion

Slide 17

Slide 17

https://blog.apisyouwonthate.com/why-do-people-dislike-jsona7d67c8d38c1

Slide 18

Slide 18

Slide 19

Slide 19

WHAT CAN WE DO?

Slide 20

Slide 20

SPECIFICATION FIRST Nothing gets implemented until the API is de ned

Slide 21

Slide 21

SPECIFICATIONS AS CONTRACTS verify that the API does what it says

Slide 22

Slide 22

Slide 23

Slide 23

GAME PLAN 1. produce the API speci cation 2. generate docs and mock API 3. re ne the speci cation 4. use it in integration tests 5. work on the actual server code

Slide 24

Slide 24

POTENTIAL BENEFITS

Slide 25

Slide 25

  1. THE SPEC IS THE SINGLE SOURCE OF TRUTH FOR OUR DESIGN

Slide 26

Slide 26

  1. ALWAYS UP TO DATE DOCUMENTATION AND TESTS

Slide 27

Slide 27

  1. WORK ON BACKEND AND CLIENTS INDEPENDENTLY

Slide 28

Slide 28

API SPECIFICATION FORMATS

Slide 29

Slide 29

Slide 30

Slide 30

API BLUEPRINT markdown based development is open on GitHub it’s quite mature there’s tooling for the most essential things mostly documentation oriented

Slide 31

Slide 31

RAML RESTful API Modeling Language yaml based syntax is quite similar to the OpenAPI Speci cation covers the whole design/development process

Slide 32

Slide 32

JSON SCHEMA not entirely fair to include it here json based focused only on the data model great for validation and tests includes syntax for describing hypermedia controls

Slide 33

Slide 33

Slide 34

Slide 34

don’t call it that please formerly known as Swagger yaml or json based very actively developed very active community

Slide 35

Slide 35

HOW TO WRITE AN OPENAPI SPECIFICATION read the spec at swagger.io/speci cation

Slide 36

Slide 36

BASIC STRUCTURE openapi: “3.0.0” info: # … servers: # … paths: # … tags: # … components: # …

Slide 37

Slide 37

LET’S BUILD A SIMPLE OPENAPI SPECIFICATION

Slide 38

Slide 38

BASIC INFORMATION ABOUT THE API info: description: >­ Imaginary API for managing meetups. Imagined for this PHPCE 2018 talk. version: ‘0.1’ title: Meetups Are Awesome API contact: email: boyan.yordanov.dev@gmail.com name: Boyan Yordanov url: ‘https://boyanyordanov.com’ license: # …

Slide 39

Slide 39

HOW CAN USERS ACCESS THE API servers: ­ url: ‘https://imaginary­meetups.com/api’ description: Imaginary API for managing Meetups ­ url: ‘https://staging.imaginary­meetups.com/api’ description: Staging server for the imaginary AP ­ url: ‘http://localhost:8080’ description: Development version of the API

Slide 40

Slide 40

it also supports templating servers: ­ url: https://{username}.api­server.com/api/ description: User specific URLs variables: username: default: demo description: assigned upon registration

Slide 41

Slide 41

WHAT CAN THE API DO

Slide 42

Slide 42

Just a list of paths and the possible requests and responses paths: /meetups # … /meetups/{id} # … /meetups/{id}/events # …

Slide 43

Slide 43

A path description /meetups: summary: meetups description: Meetups resource tags: # .. parameters: # .. get: # … post: # ..

Slide 44

Slide 44

Slide 45

Slide 45

DESCRIBING PARAMETERS /meetups: # … parameters: ­ name: city in: query / path / header description: Filter meetups based on city schema: type: string

Slide 46

Slide 46

handling array parameters /meetups: # … parameters: ­ name: technologies in: query description: Filter meetups based on city schema: type: array items: type: string style: form explode: false

Slide 47

Slide 47

Result ?technologies=php,apis,javascript

Slide 48

Slide 48

POSSIBLE RESPONSES /meetups/{id} get: responses: ‘200’: content: application/json: schema: # … ‘404’: content: application/problem+json: # …

Slide 49

Slide 49

SCHEMA OBJECTS “extended subset” of JSON Schema draft 5 support references in future will support current drafts of JSON Schema and other formats

Slide 50

Slide 50

example schema schema: type: object properties: id: type: string format: uuid name: type: string starting­date: type: string format: date

Slide 51

Slide 51

nullable elds city: description: either a string or null type: string nullable: true

Slide 52

Slide 52

other schema formats still a proposal schema: x­oas­draft­alternativeSchema: type: jsonSchema location: ./real­jsonschema.json https://github.com/OAI/OpenAPI-Speci cation/issues/1532

Slide 53

Slide 53

REFERENCE OBJECT object with $ref property reference objects in the same document reference external documents replace inline de nitions for most OpenAPI components

Slide 54

Slide 54

Replace almost anything in the spec schema: $ref: ‘#/components/schemas/Meetup’ # … responses: ‘200’: $ref: ‘MeetupsListResponse.yaml’

Slide 55

Slide 55

COMPONENTS components: schemas: # … responses: # … parameters: # … requestBodies: # … headers: # … examples: #

Slide 56

Slide 56

WE HAVE AN OPENAPI SPECIFICATION WHAT DO WE DO WITH IT?

Slide 57

Slide 57

EASY PICKINGS HTML DOCUMENTATION

Slide 58

Slide 58

Swagger UI - least favorite

Slide 59

Slide 59

Widdershins + Slate / Shins.js

Slide 60

Slide 60

REDOC

Slide 61

Slide 61

LINTER - SPECCY https://github.com/wework/speccy lints your speci cation supports rulesets docs preview with ReDoc resolve spec in one le supports external references written in json-schema

Slide 62

Slide 62

EDITORS everything supporting yaml

Slide 63

Slide 63

VSCode with openapi-lint extention validates and lints converts Swagger/OpenAPI 2.0 to OpenAPI 3.0 intellisense for both formats

Slide 64

Slide 64

Swagger Editor

Slide 65

Slide 65

Apicurio

Slide 66

Slide 66

OpenAPI GUI

Slide 67

Slide 67

SENYA EDITOR https://senya.io PhpStorm (JetBrains) plugin free for the time being smart completion live linting handles $refs well preview in Swagger UI ¯\ ( ) /¯ ツ

Slide 68

Slide 68

CODE GENERATION OPENAPI GENERATOR

Slide 69

Slide 69

community supported fork of swagger-codegen supports OpenAPI 3.0 Updated templates for different languages and frameworks

Slide 70

Slide 70

JANE-PHP/JANE-PHP https://github.com/janephp/janephp generates PSR-7 compatible SDKs can use different clients based on HTTPlug supports json-schema and OpenAPI OpenAPI v3 support was added recently

Slide 71

Slide 71

MOCK SERVERS APISprout SwaggerHub Stoplight.io

Slide 72

Slide 72

POSTMAN COLLECTIONS Apimatic.io upload/download or use API transform to and from OpenAPI lots of formats including Postman 2.0 Collections

Slide 73

Slide 73

OPENAPI / JSON SCHEMA CONVERSION https://github.com/mikunn/openapi2schema https://github.com/wework/json-schema-to-openapischema

Slide 74

Slide 74

WHY CONVERT? BEST OF BOTH WORLDS (sort of)

Slide 75

Slide 75

EXAMPLE TEST https://github.com/swaggest/php-json-schema /** @test */ public function it_tests_with_swaggest_json_schema() { $schema = $this­>loadSchema(‘events’); $response = $this­>get(‘/events’); $this­>assertValidResponse($schema, $response); }

Slide 76

Slide 76

EXAMPLE ASSERTION https://github.com/swaggest/php-json-schema protected function assertValidResponse( $schema, $response ){ $validator = Schema::import($schema); try { $data = json_decode($response­>getContent()); $validator­>in($data); $this­>assertTrue(true, ‘Something went wrong.’) } catch (InvalidValue $e) { $this­>fail($e­>getMessage()); } }

Slide 77

Slide 77

WORKING WITH THE SPECIFICATION https://github.com/apioo/psx-api Parse OpenAPI speci cation Generate from code Nice PHP API to work with the spec Supports other speci cations as well

Slide 78

Slide 78

PROOF OF CONCEPT TIME https://github.com/boyanyordanov/php-openapi-testing class ApiTest extends TestCase { use OpenAPITestTools\OpenAPIAssertions; /** @dataProvider getApiTestCases */ public function test_it_runs_openapi_based_tests( $path, $resource ) { $this­>assertValidContract($path, $resource); }

Slide 79

Slide 79

//… public function getApiTestCases(): array { $provider = new OpenAPITestTools\SpecDataProvide DIR . ‘/../../openapi.yaml’ ); return $provider­>getTestCases(); } }

Slide 80

Slide 80

MORE TOOLS OPENAPI.TOOLS thanks to Phil Sturgeon and Matthew Trask

Slide 81

Slide 81

THANK YOU! QUESTIONS? https://joind.in/talk/17ec9

Slide 82

Slide 82

RESOURCES Speci cation: https://swagger.io/speci cation https://github.com/OAI/OpenAPI-Speci cation - issues / PRs https://apisyouwonthate.com - books/blog/slack https://philsturgeon.uk https://apihandyman.io https://apievangelist.com http://json-schema.org http://www.commitstrip.com/en/2018/02/26/its-good-to-haveexperience/