<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mieszko Malawski on Medium]]></title>
        <description><![CDATA[Stories by Mieszko Malawski on Medium]]></description>
        <link>https://medium.com/@mieszkomalawski?source=rss-1219b909bc52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*73_oG0Dzs5QJ1hBIsNBFxg.jpeg</url>
            <title>Stories by Mieszko Malawski on Medium</title>
            <link>https://medium.com/@mieszkomalawski?source=rss-1219b909bc52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 16:29:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mieszkomalawski/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Contract testing REST APIs with PHP and OpenAPI]]></title>
            <link>https://medium.com/@mieszkomalawski/contract-testing-rest-apis-with-php-and-openapi-18651460840f?source=rss-1219b909bc52------2</link>
            <guid isPermaLink="false">https://medium.com/p/18651460840f</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[contract-testing]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[open-api]]></category>
            <dc:creator><![CDATA[Mieszko Malawski]]></dc:creator>
            <pubDate>Thu, 14 Mar 2019 06:53:24 GMT</pubDate>
            <atom:updated>2022-10-28T08:20:37.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*TijjlSSx9AdKv76jYFRdoQ.png" /></figure><p><strong>2022.10 Update</strong></p><p>OpenAPI-Validator package is no longer maintained. However, there are other, actively developed packages that serve similar purposes. If You wish to continue developing OpenAPI-Validator, send me a private message. Some information presented here might be outdated, however, I believe that the core idea is still very much relevant.</p><p><strong>Original article</strong></p><p>What is the most important part of a successful API? Documentation! After all, You cannot expect people to use Your API if they have to guess how to use it and work by trial and error.</p><p>Good documentation describes all the endpoints, accepted request bodies, possible responses (different bodies for different response codes), headers, authorization and most importantly: it gives some meaningful usage examples.</p><p>But what is worse than lack of documentation? Documentation <strong>that tells lies!</strong></p><h4><strong>Contract testing</strong></h4><p>These type of tests check that API behaves as described in the documentation (contract) and that we do not introduce any changes over time that might break that contract. What exactly is tested in this kind of tests?</p><ol><li>Response status code and bodies (required fields and field types)</li><li>Response Headers</li><li>Accepted request bodies</li><li>Authorization</li></ol><p>Writing these tests by hand is mundane and prone to error. Usually, it boils down to:</p><ol><li>initiate HTTP client,</li><li>call URL X with body Y</li><li>assert that response code was Z with response body AA (assert on individual fields and their types).</li></ol><p>Not only we are here duplicating what is already described in our documentation but also we can easily make a mistake here eg. forget asserting specific field etc.</p><h4><strong>How to automate it with OPENApi?</strong></h4><p>If You do not know already<a href="https://www.openapis.org/"> OPENApi</a> is as REST API specification standard. To me, its most important feature is that its readable both by humans and machines. A specification is just a YAML/JSON file that becomes our source of truth (contract). From this file, we can generate beautiful documentation using tools like <a href="https://github.com/Rebilly/ReDoc">ReDoc</a></p><p>But can we do more? Can we test that our implementation works exactly as described in the specification? Of course, we can!</p><p>Most popular contract testing tool is <a href="https://dredd.org/en/latest/">Dredd</a>, however, it does not support version 3 of OpenAPI fully yet. Also, it expects that Your API returns data exactly as described in specification examples, which IMO is not important. What&#39;s important is that data has correct fields and correct types. If You are interested in Dredd You can read <a href="https://medium.com/@m_arlandy/contract-testing-for-microservices-using-swagger-prism-and-dredd-efdd463b9433">this</a> article.</p><p>I propose an alternative solution: <a href="https://gitlab.com/mmalawski/openapi-validator">OpenAPI-validator</a></p><p>Written in PHP this library integrates easily with PHPUnit (or any other testing framework). How does this work?</p><ol><li>Instantiate it with valid OpenAPI specification</li><li>In Your test make a request using any HTTP client</li><li>Pass response method and url, validator will figure out which endpoint is tested (combination of method + url is unique across single API)</li><li>Pass response code, validator will figure which response schema should be expected</li><li>Pass response body, validator will check above mentioned schema against provided data</li><li>Validator returns a list of errors (missing fields or incorrect types)</li></ol><p>No need to write any assertions by hand. What is more interesting is that You can combine that with functional tests eg. test some feature with API and as side effect test contract.</p><h4><strong>Example</strong></h4><p>Let&#39;s say that we have API describe by following Openapi specification:</p><pre>openapi: 3.0.2<br>info:<br>  title: Cards<br>  description: Cards and decks api<br>  contact:<br>    name: Mieszko Malawski<br>  license:<br>    name: GNU AGPLv3<br>    url: https://www.gnu.org/licenses/agpl.txt<br>  version: 1.0.0<br>tags:<br>  -<br>    name: Cards<br>paths:<br>  /cards:<br>    summary: Path used to manage the list of cards.<br>    description: The REST endpoint/path used to list and create zero or more card entities.  This path contains a GET and POST operation to perform the list and create tasks, respectively.<br>    get:<br>      tags:<br>        - Cards<br>      summary: List All cards<br>      description: Gets a list of all card entities.<br>      operationId: getcards<br>      responses:<br>        200:<br>          description: Successful response - returns an array of card entities.<br>          content:<br>            application/json:<br>              schema:<br>                type: array<br>                items:<br>                  $ref: &#39;#/components/schemas/card&#39;<br>components:<br>  schemas:<br>    card:<br>      title: Root Type for card<br>      description: The root of the card type&#39;s schema.<br>      required:<br>      - id<br>      - name<br>      - power<br>      type: object<br>      properties:<br>        id:<br>          description: &quot;unique id&quot;<br>          type: string<br>          format: int64<br>          readOnly: true<br>        name:<br>          type: string<br>        power:<br>          description: &quot;how powerfull card is on the board&quot;<br>          format: int32<br>          type: integer<br>      example:<br>        id: &quot;23423423&quot;<br>        name: &quot;Geralt&quot;<br>        power: 10</pre><p>as we can there is GET /cards endpoint that allows us to fetch a list of cards. Each card has id and name which are strings and power which is an integer. This is a very simple specification but it is enough for purposes of this demo.</p><p>Our example controller:</p><pre>public function getCardsAction()<br>    {<br>        return new JsonResponse(<br>            [<br>                [<br>                    &#39;id&#39; =&gt; &#39;123123&#39;,<br>                    &#39;name&#39; =&gt; &#39;Geralt&#39;,<br>                    &#39;power&#39; =&gt; 10,<br>                ],<br>                [<br>                    &#39;id&#39; =&gt; &#39;45653&#39;,<br>                    &#39;name&#39; =&gt; &#39;Vernon Roche&#39;,<br>                    &#39;power&#39; =&gt; &#39;10&#39;,<br>                ]<br>            ]<br>        );<br>    }</pre><p>As You can see I made a mistake here: second item “power” field is a string instead of an integer. If our client happens to use strongly-typed language it can cause deserialization issue!</p><p>Our example test:</p><pre>&lt;?php<br>declare(strict_types=1);<br><br><br>namespace AppBundle\Tests\Controller;<br><br><br>use Mmal\OpenapiValidator\Validator;<br>use Symfony\Component\Yaml\Yaml;<br><br>class CardsControllerTest extends BaseControllerTest<br>{<br>    const SPEC_PATH = __DIR__.&#39;/../../../../docs/api.yml&#39;;<br>    <br>    /** @var Validator */<br>    static $openaApiValidator;<br><br>    static public function setUpBeforeClass()<br>    {<br>        parent::setUpBeforeClass();<br>        self::$openaApiValidator = new Validator(Yaml::parse(self::SPEC_PATH));<br>    }<br><br>    public function testGetCards()<br>    {<br>        $this-&gt;makeRequest(&#39;GET&#39;, &#39;/cards&#39;);<br>    }<br><br>    protected function makeRequest($method, $uri, $content = &#39;&#39;)<br>    {<br>        $client = $this-&gt;getTestClient();<br>        $client-&gt;request(<br>            $method,<br>            $uri<br>        );<br>        $response = $client-&gt;getResponse();<br><br>        $result = self::$openaApiValidator-&gt;validateBasedOnRequest(<br>            $uri,<br>            $method,<br>            $response-&gt;getStatusCode(),<br>            json_decode($response-&gt;getContent(), true)<br>        );<br>        self::assertFalse($result-&gt;hasErrors(), $result);<br><br>        return RESTResponse::fromHTTPResponse($response);<br>    }<br>}</pre><p>Let&#39;s check what happens!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSP4Sv9NsiDoLf82p1ShJw.png" /></figure><p>Great! Our validator checked that response is incorrect and violates our contract!</p><h4><strong>Final words</strong></h4><p>This library is still WIP, there is no validation for headers or request body yet. If You want to contribute or You have found any issues please don&#39;t hesitate to create issue/submit PR or contact me directly</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18651460840f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>