<?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 Dinis Esteves on Medium]]></title>
        <description><![CDATA[Stories by Dinis Esteves on Medium]]></description>
        <link>https://medium.com/@dinisjesteves?source=rss-508459fdc746------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CYfjQoAQmzIC5YR3TfN3Xg.jpeg</url>
            <title>Stories by Dinis Esteves on Medium</title>
            <link>https://medium.com/@dinisjesteves?source=rss-508459fdc746------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:23:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dinisjesteves/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[Open API and testing, a love story]]></title>
            <link>https://medium.com/@dinisjesteves/open-api-and-testing-a-love-story-b3d6fa523b4b?source=rss-508459fdc746------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3d6fa523b4b</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dinis Esteves]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 16:02:13 GMT</pubDate>
            <atom:updated>2024-01-12T09:23:23.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*EAAmCAmgcKoazBtBNWTjmg.gif" /></figure><p>For those who don’t know me my name is <a href="https://twitter.com/_est3ves">Dinis Esteves</a>, and I am a software developer at <a href="https://turbinekreuzberg.com/en">Turbine Kreuzberg</a> 🧑‍💻, this is my first blog post, so some love is truly appreciated 💚.</p><p>I’d like to discuss an intriguing approach that I’ve come across, which involves testing APIs by utilizing their Open API specifications.</p><p>For those who are not aware of it, don’t panic (yet) because I’ll share everything below.</p><h3>So, first things first? Right?</h3><h4>Open API? What is it? What are the main benefits of using it?</h4><blockquote><em>OpenAPI, formerly Swagger, revolutionizes API design and documentation. Here’s why it’s a game-changer:</em></blockquote><ul><li><strong>Consistent Design:</strong> Standardizes API design, fostering consistency across projects and enhancing collaboration among developers.</li><li><strong>Interactive Documentation:</strong> Automatically generates detailed, human-readable API documentation, saving time and ensuring clarity on endpoints, data formats, and authentication.</li><li><strong>Client Code Generation:</strong> Streamlines API consumption by automatically generating client code in multiple programming languages.</li><li><strong>Testing Efficiency:</strong> Enables early detection of issues by validating API requests and responses against the defined specification.</li><li><strong>Collaboration Boost:</strong> Facilitates improved collaboration between frontend and backend developers, enhancing communication and reducing misunderstandings.</li><li><strong>Tooling Ecosystem:</strong> Supported by a robust ecosystem of tools and libraries, offering frameworks, testing utilities, and aids in API development and maintenance.</li></ul><h4>Testing?</h4><p>I am assuming, that the vast majority of you already know about testing, for the following example I am using a <a href="https://laravel.com/">Laravel</a> application and <a href="https://pestphp.com/">Pest PHP</a> to execute tests.</p><p>Oh, PHP!? Isn’t it dead? I want to get things done, and the best way is by using Laravel. 🤭</p><h3>Talk is cheap, I’ll show you some code!</h3><p>First step, let’s scaffold everything, creating a new Laravel application called whatever:</p><pre>composer create-project laravel/laravel whatever</pre><p>Update your .env in order to use SQLite, let’s keep it simple 😉:</p><pre>DB_CONNECTION=sqlite</pre><p>Installing and initializing pest:</p><pre>composer require pestphp/pest --dev --with-all-dependencies<br><br>./vendor/bin/pest --init</pre><p>Check if everything is working as expected by running pest:</p><pre>./vendor/bin/pest</pre><p>Update your phpunit.xml so that you can run your tests using an in memory SQLite database:</p><pre>&lt;env name=&quot;DB_CONNECTION&quot; value=&quot;sqlite&quot;/&gt;<br>&lt;env name=&quot;DB_DATABASE&quot; value=&quot;:memory:&quot;/&gt;</pre><p>By default, Laravel already has a user model, so let’s take advantage of it, let’s create an auth controller with a register method, a register request to validate our request and obviously expose our method in our api.php routes:</p><pre>php artisan make:controller API/AuthController</pre><pre>&lt;?php<br><br>namespace App\Http\Controllers\API;<br>use App\Http\Controllers\Controller;<br>use App\Http\Requests\RegisterRequest;<br>use App\Models\User;<br>use Illuminate\Http\Resources\Json\JsonResource;<br><br>class AuthController extends Controller<br>{<br>  public function register(RegisterRequest $request): JsonResource<br>  {<br>    $user = User::create($request-&gt;validated());<br>    return (new JsonResource($user));<br>  }<br>}</pre><pre>php artisan make:request RegisterRequest</pre><pre>&lt;?php<br><br>namespace App\Http\Requests;<br>use Illuminate\Foundation\Http\FormRequest;<br><br>class RegisterRequest extends FormRequest<br>{<br>  /**<br>  * Determine if the user is authorized to make this request.<br>  */<br>  public function authorize(): bool<br>  {<br>    return true;<br>  }<br>  /**<br>  * Get the validation rules that apply to the request.<br>  *<br>  * @return array&lt;string, string&gt;<br>  */<br>  public function rules(): array<br>  {<br>    return [<br>      &#39;name&#39; =&gt; &#39;required|string&#39;,<br>      &#39;email&#39; =&gt; &#39;required|string|email|unique:users&#39;,<br>      &#39;password&#39; =&gt; &#39;required|confirmed&#39;<br>    ];<br>  }<br>}</pre><pre>&lt;?php<br><br>use App\Http\Controllers\API\AuthController;<br><br>Route::group([&#39;prefix&#39; =&gt; &#39;auth&#39;], function() {<br>    Route::post(&#39;register&#39;, [AuthController::class, &#39;register&#39;]);<br>});</pre><p>By now, if you execute your migrations, you can use the /api/auth/register endpoint to register new users:</p><pre>php artisan migrate</pre><p>Let’s create our API documentation following Open API specification, and create in root of our project a new spec.yaml file:</p><pre>openapi: 3.0.0<br>x-stoplight:<br>  id: a55xot39uzf7a<br>info:<br>  title: spec<br>  version: &#39;1.0&#39;<br>servers:<br>  - url: &#39;http://book.test&#39;<br>paths:<br>  /api/auth/register:<br>    post:<br>      summary: Register<br>      operationId: post-api-auth-register<br>      responses:<br>        &#39;201&#39;:<br>          description: Created<br>      description: Register a new user<br>      requestBody:<br>        content:<br>          application/json:<br>            schema:<br>              type: object<br>              properties:<br>                name:<br>                  type: string<br>                email:<br>                  type: string<br>                password:<br>                  type: string<br>                password_confirmation:<br>                  type: string<br>              required:<br>                - name<br>                - email<br>                - password<br>                - password_confirmation<br>components:<br>  schemas: {}</pre><p>Having all set up we can start creating our test. Before doing that, however, we’ll need an external library to be able to perform those tests. Let’s install it:</p><pre>composer require league/openapi-psr7-validator</pre><p>Successful installation? Let’s move on by creating our test file inside tests/Feature/AuthControllerTest.php:</p><pre>&lt;?php<br><br>use GuzzleHttp\Client;<br>use League\OpenAPIValidation\PSR7\OperationAddress;<br>use League\OpenAPIValidation\PSR7\ValidatorBuilder;<br><br>beforeEach(function () {<br>    $this-&gt;path = &#39;/api/auth/register&#39;;<br>    $this-&gt;method = &#39;post&#39;;<br>});<br><br>test(&#39;open api spec&#39;, function () {<br>    $client = new Client([&#39;base_uri&#39; =&gt; getenv(&#39;APP_URL&#39;)]);<br><br>    $request = $client-&gt;request($this-&gt;method, $this-&gt;path, [<br>        &#39;headers&#39; =&gt; [<br>            &#39;Accept&#39; =&gt; &#39;application/json&#39;,<br>            &#39;Content-Type&#39; =&gt; &#39;application/json&#39;,<br>        ],<br>        &#39;json&#39; =&gt; [<br>            &#39;name&#39; =&gt; fake()-&gt;name,<br>            &#39;email&#39; =&gt; fake()-&gt;email,<br>            &#39;password&#39; =&gt; &#39;password&#39;,<br>            &#39;password_confirmation&#39; =&gt; &#39;password&#39;,<br>        ],<br>    ]);<br><br>    $operation = new OperationAddress($this-&gt;path, $this-&gt;method);<br><br>    $validator = (new ValidatorBuilder())<br>        -&gt;fromYamlFile(&#39;spec.yaml&#39;)<br>        -&gt;getResponseValidator();<br><br>    $validator-&gt;validate($operation, $request);<br>});</pre><blockquote><strong>Note:</strong>To perform this test, your app must be running. I recommend using <a href="https://herd.laravel.com/">Herd</a> if you’re a MacOS user, if not you can use <a href="https://laravel.com/docs/10.x/sail">Sail</a>. In both cases, double-check if your APP_URL is well-defined in your .env file.</blockquote><p>If you run your tests, you should have the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knya763k9qsvYAbBvf8vVw.png" /></figure><p>Let’s make it fail: In your spec.yaml file, change the response to expect a 200 instead of a 201:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*ecQwKKaivZ5sYM7yEFwuxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a92DS1APKcUCnG-w_rskOg.png" /></figure><p>Your test will fail because the performed HTTP request is returning a 201 HTTP response code, but your spec.yaml does not contain that operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*Hy3U1YGrM_BrLJKhT9GDSw.gif" /></figure><p>You don’t like exceptions? Me either 😁 let’s change it:</p><pre>try {<br>  $validator-&gt;validate($operation, $request);<br>} catch (\Exception $e) {<br>  $this-&gt;fail($e-&gt;getMessage());<br>}</pre><p>Now, the result of your tests should look like the following one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ec1gPThdRWC8WeXn10VAwQ.png" /></figure><p>Awesome right? Let’s make it reusable, by taking advantage of <a href="https://pestphp.com/docs/custom-expectations">pest custom expectations</a>, by updating our tests/Pest.php file:</p><pre>expect()-&gt;extend(&#39;toMatchOpenApiSpec&#39;, function (string $path, string $method) {<br>    $operation = new OperationAddress($path, $method);<br><br>    $validator = (new ValidatorBuilder())<br>        -&gt;fromYamlFile(&#39;spec.yaml&#39;)<br>        -&gt;getResponseValidator();<br><br>    try {<br>        $validator-&gt;validate($operation, $this-&gt;value);<br>    } catch (\Exception $e) {<br>        test()-&gt;fail($e-&gt;getMessage());    <br>    }<br><br>    Assert::assertTrue(true);<br>});</pre><p>In your test, you can reuse the previous created expectation like this:</p><pre>&lt;?php<br><br>use GuzzleHttp\Client;<br><br>beforeEach(function () {<br>    $this-&gt;path = &#39;/api/auth/register&#39;;<br>    $this-&gt;method = &#39;post&#39;;<br>});<br><br>test(&#39;open api spec&#39;, function () {<br>    $client = new Client([&#39;base_uri&#39; =&gt; getenv(&#39;APP_URL&#39;)]);<br><br>    $request = $client-&gt;request($this-&gt;method, $this-&gt;path, [<br>        &#39;headers&#39; =&gt; [<br>            &#39;Accept&#39; =&gt; &#39;application/json&#39;,<br>            &#39;Content-Type&#39; =&gt; &#39;application/json&#39;,<br>        ],<br>        &#39;json&#39; =&gt; [<br>            &#39;name&#39; =&gt; fake()-&gt;name,<br>            &#39;email&#39; =&gt; fake()-&gt;email,<br>            &#39;password&#39; =&gt; &#39;password&#39;,<br>            &#39;password_confirmation&#39; =&gt; &#39;password&#39;,<br>        ],<br>    ]);<br><br>    expect($request)<br>        -&gt;toMatchOpenApiSpec($this-&gt;path, $this-&gt;method);<br>});</pre><p>Let’s create another test case so that we can use our open API spec to validate multiple use cases:</p><pre>it(&#39;returns error bag when missing required body properties&#39;, function () {<br>    $client = new Client([&#39;base_uri&#39; =&gt; getenv(&#39;APP_URL&#39;), &#39;http_errors&#39; =&gt; false]);<br>    <br>    $request = $client-&gt;request($this-&gt;method, $this-&gt;path, [<br>        &#39;headers&#39; =&gt; [<br>            &#39;Accept&#39; =&gt; &#39;application/json&#39;,<br>            &#39;Content-Type&#39; =&gt; &#39;application/json&#39;,<br>        ],<br>        &#39;json&#39; =&gt; [<br>            &#39;name&#39; =&gt; fake()-&gt;name,<br>            &#39;email&#39; =&gt; fake()-&gt;email,<br>            &#39;password&#39; =&gt; &#39;password&#39;,<br>        ],<br>    ]);<br><br>    expect($request)<br>        -&gt;toMatchOpenApiSpec($this-&gt;path, $this-&gt;method);<br><br>    expect($request-&gt;getBody()-&gt;getContents())<br>        -&gt;json()<br>        -&gt;message-&gt;toBeString()<br>        -&gt;errors-&gt;toBeArray();<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*IFLnKQOoG291t5ZaCP1gqA.png" /></figure><p>Now our test is failing because Open API spec does not contain the 422 response code, by adding it your test will turn green:</p><pre>responses:<br>  &#39;201&#39;:<br>    description: Created<br>  &#39;422&#39;:<br>    description: Unprocessable Entity</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*vuddic0_fGsYnhNkpCWwxw.png" /></figure><h3>Insights &amp; Takeaways</h3><p>Using Open API can leverage your development consistency. This blog post gives you a clear example on how you can use it in order to take advantages when testing your endpoints. Nothing is written in stone, and I truly believe that testing endpoints against an Open API spec is a great way of keeping consistency in our projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*cpfnxRK61MQLUwT9euQJcg.gif" /></figure><p>Thanks for your time 🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3d6fa523b4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>