A presentation at PHP CE in in Prague, Czechia by Boyan Yordanov
BEYOND DOCUMENTATION WITH OpenAPI
GET /SPEAKERS/BOYAN Boyan Yordanov @specter_bg PHP Varna and VarnaJS organizer VarnaLab member Developer@ShtrakBG
WHO LIKES WRITING DOCUMENTATION?
DOCUMENTATION THAT IS: “too long to read” “totally useless” “not updated”
JUST BORING
API SPECIFICATIONS machine readable easy to write more than documentation
I still have to write it, though. - me
I can do so many cool things with this de nition. - also me (a couple of months later)
WHY BOTHER WITH AN API SPECIFICATION?
HAVE YOU BEEN THIS PERSON? http://www.commitstrip.com
HOW ABOUT THIS?
OUR PROCESS HAS FAILED US
WASTED TIME AND A LOT OF FRUSTRATION
COMMON PROBLEMS changes aren’t properly tested clients constantly wait for the API documentation and code don’t match SDKs have another opinion
https://blog.apisyouwonthate.com/why-do-people-dislike-jsona7d67c8d38c1
WHAT CAN WE DO?
SPECIFICATION FIRST Nothing gets implemented until the API is de ned
SPECIFICATIONS AS CONTRACTS verify that the API does what it says
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
POTENTIAL BENEFITS
API SPECIFICATION FORMATS
API BLUEPRINT markdown based development is open on GitHub it’s quite mature there’s tooling for the most essential things mostly documentation oriented
RAML RESTful API Modeling Language yaml based syntax is quite similar to the OpenAPI Speci cation covers the whole design/development process
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
don’t call it that please formerly known as Swagger yaml or json based very actively developed very active community
HOW TO WRITE AN OPENAPI SPECIFICATION read the spec at swagger.io/speci cation
BASIC STRUCTURE openapi: “3.0.0” info: # … servers: # … paths: # … tags: # … components: # …
LET’S BUILD A SIMPLE OPENAPI SPECIFICATION
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: # …
HOW CAN USERS ACCESS THE API servers: url: ‘https://imaginarymeetups.com/api’ description: Imaginary API for managing Meetups url: ‘https://staging.imaginarymeetups.com/api’ description: Staging server for the imaginary AP url: ‘http://localhost:8080’ description: Development version of the API
it also supports templating servers: url: https://{username}.apiserver.com/api/ description: User specific URLs variables: username: default: demo description: assigned upon registration
WHAT CAN THE API DO
Just a list of paths and the possible requests and responses paths: /meetups # … /meetups/{id} # … /meetups/{id}/events # …
A path description /meetups: summary: meetups description: Meetups resource tags: # .. parameters: # .. get: # … post: # ..
DESCRIBING PARAMETERS /meetups: # … parameters: name: city in: query / path / header description: Filter meetups based on city schema: type: string
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
Result ?technologies=php,apis,javascript
POSSIBLE RESPONSES /meetups/{id} get: responses: ‘200’: content: application/json: schema: # … ‘404’: content: application/problem+json: # …
SCHEMA OBJECTS “extended subset” of JSON Schema draft 5 support references in future will support current drafts of JSON Schema and other formats
example schema schema: type: object properties: id: type: string format: uuid name: type: string startingdate: type: string format: date
nullable elds city: description: either a string or null type: string nullable: true
other schema formats still a proposal schema: xoasdraftalternativeSchema: type: jsonSchema location: ./realjsonschema.json https://github.com/OAI/OpenAPI-Speci cation/issues/1532
REFERENCE OBJECT object with $ref property reference objects in the same document reference external documents replace inline de nitions for most OpenAPI components
Replace almost anything in the spec schema: $ref: ‘#/components/schemas/Meetup’ # … responses: ‘200’: $ref: ‘MeetupsListResponse.yaml’
COMPONENTS components: schemas: # … responses: # … parameters: # … requestBodies: # … headers: # … examples: #
WE HAVE AN OPENAPI SPECIFICATION WHAT DO WE DO WITH IT?
EASY PICKINGS HTML DOCUMENTATION
Swagger UI - least favorite
Widdershins + Slate / Shins.js
REDOC
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
EDITORS everything supporting yaml
VSCode with openapi-lint extention validates and lints converts Swagger/OpenAPI 2.0 to OpenAPI 3.0 intellisense for both formats
Swagger Editor
Apicurio
OpenAPI GUI
SENYA EDITOR https://senya.io PhpStorm (JetBrains) plugin free for the time being smart completion live linting handles $refs well preview in Swagger UI ¯\ ( ) /¯ ツ
CODE GENERATION OPENAPI GENERATOR
community supported fork of swagger-codegen supports OpenAPI 3.0 Updated templates for different languages and frameworks
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
MOCK SERVERS APISprout SwaggerHub Stoplight.io
POSTMAN COLLECTIONS Apimatic.io upload/download or use API transform to and from OpenAPI lots of formats including Postman 2.0 Collections
OPENAPI / JSON SCHEMA CONVERSION https://github.com/mikunn/openapi2schema https://github.com/wework/json-schema-to-openapischema
WHY CONVERT? BEST OF BOTH WORLDS (sort of)
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); }
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()); } }
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
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); }
//… public function getApiTestCases(): array { $provider = new OpenAPITestTools\SpecDataProvide DIR . ‘/../../openapi.yaml’ ); return $provider>getTestCases(); } }
MORE TOOLS OPENAPI.TOOLS thanks to Phil Sturgeon and Matthew Trask
THANK YOU! QUESTIONS? https://joind.in/talk/17ec9
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/
Imagine a world where the mobile development team is not constantly surprised by changing endpoints, where frontend developers don’t abuse your carefully crafted APIs and we don’t have to go back again and again to fix or change stuff. In this imaginary land we are able to leave the guesswork out by using API definitions to produce even better designs and automate parts of the process. Together we will explore OpenAPI as a standard way to describe APIs and see how it can help us get there.
Here’s what was said about this presentation on social media.
Time to listen about OpenAPI from @specter_bg at #phpce18 pic.twitter.com/SKm4q8MyLw
— Alexander Lisachenko (@lisachenko) October 28, 2018
"Everything around us is some kind of API" @specter_bg #phpce18 #phpce
— Nikola Dimitrijević (@buki_zvani_pera) October 28, 2018
Don't call openAPI swagger @phpce_eu #phpce18 @specter_bg pic.twitter.com/MydjZMvF9r
— Milko Kosturkov (@mkosturkov) October 28, 2018