<?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"><channel><title><![CDATA[Beppe is Here]]></title><description><![CDATA[APIs, OpenAPI and stuff]]></description><link>https://beppecatanese.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 14 Nov 2026 14:10:13 GMT</lastBuildDate><atom:link href="https://beppecatanese.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[✨ The 7 Golden Rules for Creating API Libraries that Shine ✨]]></title><description><![CDATA[Discover 7 essential rules for creating API libraries with optimal developer experience, focusing on OpenAPI, idiomatic code, documentation, and more]]></description><link>https://beppecatanese.hashnode.dev/api-libraries-7-golden-rules</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/api-libraries-7-golden-rules</guid><category><![CDATA[APIs]]></category><category><![CDATA[Libraries]]></category><category><![CDATA[OpenApi]]></category><category><![CDATA[developer experience]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Fri, 15 Nov 2024 09:26:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Sj0iMtq_Z4w/upload/0487291aacdea3ce5bf3012424e31feb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>API libraries are essential in making APIs accessible to every developer. They create an <strong>abstraction</strong> that simplifies how applications interact with services. They boost <strong>productivity</strong> by fitting in the developer’s preferred language and technology stack. They let developers focus on creating <strong>business value</strong> instead of worrying about repetitive work and boilerplate code.</p>
<p>However, creating a successful API library is more than just wrapping API calls. It’s about understanding the audience’s needs and pain points to deliver an <strong>optimal developer experience</strong>.</p>
<blockquote>
<p><strong>In this article…</strong> discover the 7 Golden Rules for designing API Libraries that make Developer Experience a top priority. Based on a true story (Adyen 💚).</p>
</blockquote>
<p>Read below the benefits, challenges and tips of the 7 golden rules:</p>
<ol>
<li><p>OpenAPI Driven</p>
</li>
<li><p>Idiomatic</p>
</li>
<li><p>Release Notes and Breaking Changes guide</p>
</li>
<li><p>Code snippets</p>
</li>
<li><p>Reference implementation</p>
</li>
<li><p>Deprecation strategy</p>
</li>
<li><p>Great documentation</p>
</li>
</ol>
<h3 id="heading-1-openapi-driven">1. OpenAPI Driven</h3>
<p>Nowadays, there are other options than writing the source code of the libraries from scratch. First, in any modern platform, API release cycles are short, and teams frequently introduce new features and changes. Second, accuracy is crucial: as we add functions, objects, and fields, we must ensure they consistently represent the API behaviour.</p>
<p>📣 Enter OpenAPI.</p>
<p>The answer is automated code generation. The source code can be generated by leveraging an OpenAPI specification and choosing the right tool (<a target="_blank" href="https://github.com/openapitools/openapi-generator/">OpenAPI Generator</a>, <a target="_blank" href="https://www.apimatic.io/product/generate#sdk">APIMatic</a>, etc.).</p>
<p>These generators support multiple languages, are customisable, and can be integrated into a CI/CD pipeline.</p>
<p>How does it then work? Once the OpenAPI contract is finalised (whether you’re <a target="_blank" href="https://blog.stoplight.io/api-first-api-design-first-or-code-first-which-should-you-choose">design-first or code-first</a>), a pipeline triggers the code generation, followed by testing and releasing.</p>
<p>What happens next is the exciting part: as we need to evolve the API or address an issue, we go back to the drawing board and update the OpenAPI specification. There are no manual changes (except for some utilities and helpers outside the code generation), but the update follows the OpenAPI-driven lifecycle.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*kAEPMayI3z7ddTpGBkOKrA.png" alt="Lifecycle of the OpenAPI-driven library" class="image--center mx-auto" /></p>
<p>Lifecycle of the OpenAPI-driven library — Image by author</p>
<p>The benefits are clear:</p>
<ul>
<li><p>Automation: OpenAPI specs are converted to working code in an automated fashion, cutting significantly the release cycle (and effort) of the libraries</p>
</li>
<li><p>Consistency: The generated source code reflects the API contracts, removing discrepancies between consumers and producers.</p>
</li>
</ul>
<h4 id="heading-tips">Tips</h4>
<p><strong>Invest in the source code templates</strong></p>
<p>The generated source code is based on code templates provided by the generators. However, you want to control the output (package structure, naming conventions, signature of the methods, comments, documentation, etc.), so the first essential step is to override the default templates.</p>
<p><strong>Generator upgrades</strong></p>
<p>Your generator of choice will keep evolving, and it’s essential to ensure that your custom templates remain compatible. <strong>Stay proactive</strong>, follow the upgrades, adjust your templates, and define a good testing strategy that verifies those upgrades don’t affect your library.</p>
<p><strong>Code duplication</strong></p>
<p>Code duplication is often seen as a critical metric in assessing software health. However, a different perspective is necessary when it comes to auto-generated code. The code templates process a list of endpoints and models, creating consistent and repeatable code blocks. As a result, code duplication becomes a “necessary evil.” The primary goal is to provide consistent, readable code; duplication should not compromise that.</p>
<p><strong>Adjust your metrics</strong> accordingly to align with this approach. Tune SonarQube and other static code analysis tools to disregard duplication and focus instead on other metrics.</p>
<p><strong>Drop and (re)generate</strong></p>
<p>Before generation, remove all previously generated code, including services (endpoints) and models. This ensures that the library will contain only the operations and entities found in the OpenAPI specifications. Any elements deleted from the API contract must also be removed from the library.</p>
<p><strong>Living downstream</strong></p>
<p>SDKs are downstream products of APIs, which increases the complexity of development. API teams may add new models instead of reusing existing ones or overlook naming conventions (tip: enable a good linting mechanism), impacting the quality of the generated source code. Ensure you’re heard: state your requirements, emphasise the potential impact on the libraries and their users, and establish a feedback loop.</p>
<h3 id="heading-2-idiomatic-code">2. Idiomatic Code</h3>
<p>Libraries are powerful because they fit in the technical context that developers are familiar with. Therefore, we need to ensure the generated code is crafted for the programming language it’s targeting.</p>
<p>An API library should align with the language’s conventional practices:</p>
<ul>
<li><p><strong>Naming Conventions</strong>: adopt the expected style guides (e.g. camelCase in JavaScript, snake_case in Python).</p>
</li>
<li><p><strong>Error Handling</strong>: implement the property mechanisms for error handling (e.g. exceptions in Python, error values in Go).</p>
</li>
<li><p><strong>Data Types</strong>: use native data structures to keep code readable and intuitive.</p>
</li>
<li><p><strong>Language Features</strong>: Rely on the features of the language (e.g. different languages have different approaches to enums), making it easier for developers to understand and adopt the library.</p>
</li>
</ul>
<h4 id="heading-tips-1">Tips</h4>
<p><strong>Multiple languages</strong></p>
<p>For teams that support multiple programming languages, it can be tempting to streamline the code generation by consolidating common aspects — for example, handling enums or comments in the same way across languages. However, this approach risks producing “foreign” code that doesn’t feel natural for the developers.</p>
<p>Start by always defining the desired output for each language and design your templates accordingly. Ensure the team is building strong expertise in each supported language. Rather than automating for simplicity or speed, <strong>focus on quality</strong>: keep revising the generated source code, adapt it to each language, and strive to deliver an experience that is aligned with the language’s conventions and idioms.</p>
<p><strong>Dependencies and frameworks</strong></p>
<p>Ideally, your library should be simple and lightweight. In practice, however, most languages are popular because of the rich ecosystem of frameworks and utilities. Try to minimise dependency imports, but make intentional choices when needed: frameworks can give developers a significant advantage.</p>
<p>Sometimes, it’s best to give developers flexibility — for example, by letting them choose their own JSON serialising library. In other scenarios, leveraging a popular framework can improve usability and simplify the integration.</p>
<h3 id="heading-3-release-notes-and-breaking-changes">3. Release Notes and Breaking Changes</h3>
<p>The OpenAPI-driven approach increases the speed of delivery, which brings the challenge of providing good release notes for each new release.</p>
<p>New features must be documented, and changes should be explained. When introducing <strong>breaking changes</strong>, a robust API library handles the upgrade, clarifying the migration path and trying to minimise disruption in the existing applications.</p>
<h4 id="heading-tips-2">Tips</h4>
<p>Producing practical release notes is not trivial. It requires a careful analysis of the OpenAPI changes and a thorough review of extensive Git diffs to understand and summarise the changes introduced in each release.</p>
<p>Consider adopting a tool like OpenAPI, such as <a target="_blank" href="https://github.com/OpenAPITools/openapi-diff">OpenAPI Diff</a> or <a target="_blank" href="https://www.oasdiff.com/">OAS Diff</a>. This tool can produce a detailed comparison between two versions of the same OpenAPI specification. The overview helps pinpoint changes that must be highlighted or explained in the release notes.</p>
<h3 id="heading-4-code-snippets">4. Code Snippets</h3>
<p>Good examples make a library accessible to all levels of developers; therefore, providing code snippets is essential to show how to use the library effectively.</p>
<p>Snippets are best placed within the product documentation. As developers learn the features and what to expect, the code snippets clearly indicate how simple it’s to use the library.</p>
<p>When you support SDKs in multiple languages, the snippets should be provided in different languages.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*mbYpfIO9OoPbgUuNKRJ15g.png" alt="Code snippets in multiple languages" class="image--center mx-auto" /></p>
<p>Code snippets in multiple languages — image by author</p>
<p>What makes a good code snippet:</p>
<ul>
<li><p>it compiles and runs</p>
</li>
<li><p>it’s concise but remains clear and readable</p>
</li>
<li><p>it includes everything the developers need (imports, variable declarations, etc.)</p>
</li>
<li><p>it’s ready to go (a.k.a. copy-paste)</p>
</li>
</ul>
<h4 id="heading-what-about-unit-testing">What about Unit testing</h4>
<p>Unit testing (because who doesn’t love unit testing?) is also a powerful way to provide code snippets. As we increase test coverage, we give the developers more examples to learn from.</p>
<p>Unit tests invoke library features exactly as developers would, serving as a blueprint. In any open-source library, unit tests should become a <strong>public catalog of working snippets</strong>, demonstrating how to use the library effectively. That’s another good reason to invest in unit testing.</p>
<h4 id="heading-tips-3">Tips</h4>
<p>As the API evolves, so must the SDK and code snippets. Manually crafting these snippets (similar to Release Notes) can be tedious and costly, so we need an automation strategy. With an OpenAPI-driven approach, the OpenAPI specification is the single source of truth. By leveraging the examples in the OpenAPI file, we can generate code snippets that developers can use. When new API versions are released, the code generator updates the snippets and archives previous versions to maintain a comprehensive version history.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*mlrqKDLOt8mopEu6ZJFlhw.png" alt="The Golden OpenAPI pipeline " class="image--center mx-auto" /></p>
<p>The Golden OpenAPI pipeline — image by author</p>
<h3 id="heading-5-reference-implementation">5. Reference implementation</h3>
<p>Nothing beats working code 🤓.</p>
<p>The most effective “Getting Started” guide is a sample application that demonstrates the library in action and covers the key use cases and workflows.</p>
<p>With the source code available on GitHub, developers can easily view what the library can do by cloning or forking the repository. They can explore the code, run the application, try out the features, and copy the code snippets.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*xgDBNHoefy4KIUJh9hmXPA.png" alt="Adyen Sample app on GitHub" class="image--center mx-auto" /></p>
<p>Adyen Sample app on GitHub — image by author</p>
<h4 id="heading-tips-4">Tips</h4>
<p>Make the application available on Gitpod or Codespaces to allow developers to launch the application effortlessly.</p>
<p>Update the reference implementation when a new library release is published. This will showcase the <strong>library upgrade</strong> and provide developers with valuable information about the impact of the changes introduced in new releases.</p>
<h3 id="heading-6-provide-deprecation-markers">6. Provide Deprecation Markers</h3>
<p>Deprecation markers are necessary to guide developers when parts of an API become obsolete. The API library should follow language-specific conventions and mark the deprecated code accordingly.</p>
<h4 id="heading-tips-5">Tips</h4>
<p>OpenAPI supports deprecation for operations and fields, so during the code generation, ensure these tags are translated into language-specific annotations. If the OpenAPI file includes custom extensions, for example, a deprecation message (<code>x-deprecatedMessage</code>), configure the code generation to incorporate these messages and give developers extra context — directly inside the library’s source code and visible in the IDE.</p>
<h3 id="heading-7-great-documentation">7. Great Documentation</h3>
<p>Great products need excellent documentation. Developers will inevitably land on the documentation page, whether they’re looking to get started or for guidance on optimisation or advanced features.</p>
<p>Documentation should serve as the gateway to the library, offering:</p>
<ul>
<li><p>comprehensive guides to get started, integrate seamlessly, and make the most of the library</p>
</li>
<li><p>code snippets that show practical usage</p>
</li>
<li><p>links to source code on GitHub and the OpenAPI specifications</p>
</li>
<li><p>easy access to additional resources, including release notes, reference implementations, blogs, and videos</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>A successful API library goes beyond simply wrapping API endpoints; it prioritises developer experience. This means maintaining short release cycles while delivering high-quality code, offering code snippets and working samples, deprecation information, release notes, and excellent documentation.</p>
<p>Check out the ✨ 7 Golden Rules ✨ of API libraries, and let me know what else we can do to help developers create the best API integrations.</p>
]]></content:encoded></item><item><title><![CDATA[Redefine API Testing with the OpenAPI workflows]]></title><description><![CDATA[An ever-changing game — like football]]></description><link>https://beppecatanese.hashnode.dev/redefine-api-testing-with-the-openapi-workflows</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/redefine-api-testing-with-the-openapi-workflows</guid><category><![CDATA[APIs]]></category><category><![CDATA[OpenApi]]></category><category><![CDATA[Testing]]></category><category><![CDATA[workflow]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Fri, 23 Feb 2024 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/gNgPY1axBkU/upload/8b94f4ddb30b273de4a0d431884ec597.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Football, similarly to many other sports, has been continuously changing. The beautiful game had to adapt to changes in the players’ abilities, the clubs’ ambitions, and the demands and expectations of its supporters and lovers.</p>
<p>But there have been, at times, changes that have drastically transformed the sport. Not many will remember the times before the back-pass rule: the goalkeeper was allowed to handle the ball even when this was a pass from one of the teammates. That led to time-wasting and slowing down the rhythm, significantly affecting the speed of the game.</p>
<p>Nothing has been the same since that day: goalkeepers learned to master the ball with their feet, and the game has become much faster while matches are more exciting.</p>
<p>And the best part of it is that we all have won, no matter which team you supported or which player you would dream to be.</p>
<p>Can the API ecosystem undergo a similar transformation? Will <strong>API workflows</strong> create opportunities that benefit everyone — be it applications, tools, or users?</p>
<p><strong>In this blog…</strong></p>
<blockquote>
<p>…read about the <a target="_blank" href="https://github.com/OAI/sig-workflows">OpenAPI Workflow</a> specification, its use cases, and the opportunities it can bring to API Testing.</p>
</blockquote>
<h3 id="heading-api-testing">API Testing</h3>
<p>APIs are the backbone of any modern platform. They enable seamless communication between users and applications, secure data exchange, and connect systems and partners. But, as the communication patterns become more complex and the use cases more advanced, API testing is more crucial than ever.</p>
<p>API testing is not the newest topic. We have all been doing this for a while, engineering the approach as we go, trying tools, and learning best practices. However, the focus has always been on ensuring an endpoint respects its contract. While this approach is valuable for validating the correctness of individual API calls, it falls short of validating the holistic behaviour of the API.</p>
<h4 id="heading-contract-testing"><strong>Contract Testing</strong></h4>
<p>Take Contract Testing. It’s a well-established discipline in the API testing arena. The API team provides a contract (such as an OpenAPI definition), and both the consumer and producer mutually agree upon it. No exception, not even a small one.</p>
<p>The way this works is pretty simple. The OpenAPI standard lets you define examples that provide a request-response interaction: when providing a specific JSON payload for an operation, it would return a given response. The more examples, the more interactions you can test.</p>
<p>For example: the <a target="_blank" href="https://github.com/adyen/adyen-openapi">Adyen Checkout OpenAPI file</a> gives you an exhaustive list of payment scenarios. Developers look at those examples to understand the type and format of the data being exchanged, while tools use these expectations to verify the behaviour (contract) of the API.</p>
<p>Several tools are doing a great job in this domain. Some of them also work without OpenAPI, allowing us to define the expectations differently through some metalanguage or custom code. They are all good at what they do. Unfortunately, that is <strong>testing a single API call</strong> at the time.</p>
<h3 id="heading-enter-openapi-workflows"><strong>Enter OpenAPI workflows</strong></h3>
<p>If you haven’t heard of it yet, watch now the 𝗧𝗵𝗲 𝗔𝗣𝗜 𝗪𝗼𝗿𝗸𝗳𝗹𝗼𝘄𝘀 𝗦𝗽𝗲𝗰𝗶𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻: 𝗧𝗵𝗲 𝗺𝗶𝘀𝘀𝗶𝗻𝗴 𝗽𝗶𝗲𝗰𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗔𝗣𝗜 𝗽𝘂𝘇𝘇𝗹𝗲 talk <a target="_blank" href="https://www.youtube.com/watch?v=NdlhxIVlSEM&amp;t=2s">https://www.youtube.com/watch?v=NdlhxIVlSEM&amp;t=2s</a> given by Frank Kilcommins (SmartBear) at API Days Paris 2023.</p>
<p>In a nutshell, the goal of the OpenAPI workflow specification is to describe, in a machine-readable format, a chain of API requests. It is no longer about sending some input and receiving an output. It’s about representing a sequence of API calls that collectively fulfil a business process. Each API call is one of those steps towards delivering the intended business value.</p>
<p>OpenAPI workflow files can be written in JSON or YAML, and include several elements:</p>
<ul>
<li><p><code>workflowSpec</code>: the version of the workflow specification the file implements.</p>
</li>
<li><p><code>info</code>: the usual (essential) metadata like title, version, and description.</p>
</li>
</ul>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*Q9apeXPOrXoWiQb9rh2QYQ.png" alt /></p>
<p>Info (api-flows.com)</p>
<ul>
<li><p><code>sourceDescriptions</code>: the sources that will be used in the workflow specification file. Think of the OpenAPI document that describes the operations invoked by the workflow.</p>
</li>
<li><p><code>workflows</code>: one or more workflows. Each workflow specifies the steps (API calls) and their input, output, and expectations.</p>
</li>
</ul>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*AH7Wu-iN5cra_Fy8OLqSBg.png" alt /></p>
<p>Workflows (api-flows.com)</p>
<ul>
<li><code>components</code>: re-usable parameters and objects</li>
</ul>
<h4 id="heading-use-cases"><strong>Use cases</strong></h4>
<p>Some use cases are immediately visible, and surely new ones will emerge as the adoption starts.</p>
<p>Start with the <strong>visual representation</strong> of API-driven processes: this makes clear to consumers how they will interact with multiple services. That is a significant advancement in developer experience, as developers no longer need to figure out (reading the docs or the OpenAPI endpoint specs) the order, data format, and expectation of each step.</p>
<p>I look forward to seeing how the standard will help <strong>AI agents</strong> better understand services that can be plugged into a conversation (e.g., “Hey chatbot, find me the best deals! “). AI agents are quickly becoming the largest consumer of APIs; chatbots engage users, perform actions on their behalf, or retrieve data during the conversation. The OpenAPI workflows can play a significant role here, providing the semantics necessary to use the APIs.</p>
<p>Finally, the <strong>API testing</strong> use case is where the OpenAPI workflow can bring real innovation. The API users should be able to define the sequence of API calls (mimic the way they are going to use them) and make those flows testable, repeatable and automated.</p>
<h3 id="heading-consumer-driven-api-testing"><strong>Consumer-Driven API Testing</strong></h3>
<p>Let’s consider an e-commerce application with functionalities such as user authentication, product browsing, placing an order, and checkout. Instead of testing each API endpoint in isolation and verifying its contract, developers can define an OpenAPI workflow encompassing the entire shopping process. This holistic approach allows for identifying integration issues, data inconsistencies, and side effects that may arise only when multiple APIs are involved.</p>
<p>OpenAPI workflows will facilitate <strong>consumer-driven testing</strong>, where the consumers can define machine-readable test scenarios that have all the information: operations, order, data format, and expectations.</p>
<p>As a developer consuming multiple APIs, I want to be in the position to script the API flows that I support. I want to test those in an automated fashion. I need to make sure they function as expected from the end-user perspective. I want to run scenarios that are supposed to fail because of the input, the order of the steps, or other factors.</p>
<p>I compare (in a way) the OpenAPI workflows to a test plan that can assert different scenarios, starting from the happy flows as well as exploring the potential errors that might arise.</p>
<h4 id="heading-assertion-verification"><strong>Assertion Verification</strong></h4>
<p>In the context of API testing, how the OpenAPI workflow specification supports data-driven verification is crucial. This is achieved by letting developers specify the validation criteria within each workflow step.</p>
<p>The <code>SuccessCriteria</code> element is a list of assertions that establish whether the step has succeeded. Each assertion is defined as a <a target="_blank" href="https://github.com/OAI/sig-workflows/blob/main/versions/1.0.0.md#runtime-expressions">Runtime Expression</a>, a condition computed using the information available as the step is executed.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*ZdvzLo6aFJKKW3QT1OhHNA.png" alt /></p>
<p>SuccessCriteria (<code>api-flows.com</code>)</p>
<p>In the example above, the step must:</p>
<ul>
<li><p>return a response with HTTP Status Code 200</p>
</li>
<li><p>find a specific reference in the response body</p>
</li>
<li><p>match a second reference with the initial data inputs defined in the workflow.</p>
</li>
</ul>
<p>Let’s go back to the e-commerce application mentioned earlier. Developers will be able to define assertions to validate the correctness of product prices, the details of the order being placed, and the payment outcome. By embedding such assertions into the OpenAPI workflow, developers can automatically detect discrepancies from the expected behaviour and pinpoint exactly where the issues occur within the user journey.</p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>In summary, the advent of the OpenAPI workflows can fundamentally evolve API testing practices. By moving beyond testing individual endpoints to embracing a scenario-driven approach, developers can verify their APIs against real-world scenarios. Being in a machine-readable format the OpenAPI workflow can become effective test plans that are automated to ensure continuous verification.</p>
<p>As software systems continue to grow in complexity, orchestrating multiple APIs and re-using services from different platforms, the OpenAPI workflows can create the framework to validate the correctness and effectiveness of these interactions.</p>
<p>I am looking forward to seeing if and how tools, vendors, and the whole API ecosystem will understand the massive opportunity and adopt a new approach to API testing. The OpenAPI workflow specification is here, and the first step is taken. Let’s see what unfolds next.</p>
]]></content:encoded></item><item><title><![CDATA[Pushing OpenAPI files to Postman]]></title><description><![CDATA[Seamless integration with a GitHub action]]></description><link>https://beppecatanese.hashnode.dev/pushing-openapi-files-to-postman</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/pushing-openapi-files-to-postman</guid><category><![CDATA[Postman]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[github-actions]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Mon, 09 Oct 2023 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/BIk2ANMmNz4/upload/d063e8a81bd17bb4d60ac5ebfe90a399.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>For the OpenAPI adopters, the OpenAPI specification is the source of truth. The specification is the contract we offer to our APIs' consumers. It can be published as documentation but also consumed by other tools to provide additional value in terms of developer experience (think of an API dashboard or SDK generation), collaboration (shared on Postman) or testing (mocks and contract testing).</p>
<h4 id="heading-in-this-article">In this article…</h4>
<blockquote>
<p>..read how an OpenAPI file can be converted in a Postman collection and, using a Github workflow, pushed seamlessly to postman.com. Checkout the different steps involved and eventually build your own workflow.</p>
</blockquote>
<h3 id="heading-the-use-case">The use case</h3>
<p>You are a spec-first developer in an API-first organisation. You build in public and make your API contracts available on GitHub. Additionally, you provide updated Postman collections to empower API consumers in their exploration, adoption and integration.</p>
<p>You understand that manual tasks are both laborious and prone to errors, which can be detrimental when striving for speed, efficiency and scalability. <strong>You don’t want to automate, you need to.</strong></p>
<p>The automated conversion from OpenAPI to Postman ensures the alignment between the tools you provide and the API specification. There’s no room for discrepancies, and your investment in a well-crafted OpenAPI design, that includes reusable objects and multiple examples, pays off.</p>
<p>Seamlessly publishing the Postman collections ensures your audience has the necessary tools and resources as quickly as possible.</p>
<p>This approach leads to less effort and greater speed. Let’s see how it can be implemented.</p>
<h3 id="heading-the-github-workflow">The GitHub workflow</h3>
<p>The GitHub workflow includes 3 steps:</p>
<ul>
<li><p>checkout the repository</p>
</li>
<li><p>generate the Postman collection as JSON</p>
</li>
<li><p>push the JSON file to your Postman workspace</p>
</li>
</ul>
<p>Below you can find the entire workflow file. In the upcoming sections, we look at what each step entails.</p>
<pre><code class="lang-bash">name: <span class="hljs-string">"From OpenAPI file to Postman"</span>

on:
  workflow_dispatch:
    inputs:
      file:
        description: <span class="hljs-string">'OpenAPI filepath'</span>     
        required: <span class="hljs-literal">true</span>
        default: <span class="hljs-string">'test/openapi/test.yml'</span>
<span class="hljs-built_in">jobs</span>:
  generate:
    name: <span class="hljs-string">"Generate Postman Collection"</span>
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repo    
        uses: actions/checkout@v3
        with:
          fetch-depth: 2
      - name: Generate postman.json    
        uses: addnab/docker-run-action@v3
        with:
          image: openapitools/openapi-generator-cli
          options: -v <span class="hljs-variable">${{ github.workspace }</span>}:/<span class="hljs-built_in">local</span>
          run: |
            <span class="hljs-built_in">echo</span> <span class="hljs-string">"Generate postman.json from <span class="hljs-variable">${{ github.event.inputs.file }</span>}"</span>
            /usr/<span class="hljs-built_in">local</span>/bin/docker-entrypoint.sh generate -i /<span class="hljs-built_in">local</span>/<span class="hljs-variable">${{ github.event.inputs.file }</span>} -g postman-collection -o /<span class="hljs-built_in">local</span>/out
      - name: Push to Postman    
        uses: gcatanese/push-to-postman-action@main
        with:
          goal: createOrUpdate
          postman-key: <span class="hljs-variable">${{ secrets.POSTMAN_API_KEY }</span>}
          postman-file: <span class="hljs-variable">${{ github.workspace }</span>}/out/postman.json
          workspace-id: <span class="hljs-variable">${{ secrets.POSTMAN_WORKSPACE_ID }</span>}
</code></pre>
<h4 id="heading-inputs-and-variables">Inputs and variables</h4>
<p>First of all, let’s see which are the <strong>inputs</strong> that the workflow requires. In this example, we assume running the workflow manually( <code>workflow_dispatch</code> ) so we are going to provide, as input, the path of the OpenAPI file.</p>
<p>Being mandatory, it must be provided before running the workflow, and it can be used using the notation <code>${{ github.event.inputs.file }}</code> .</p>
<p>We also need the variables that define settings like the Postman API key and the Postman workplace ID. Those are configured as repository secrets and can be used using the notation <code>${{ secrets.POSTMAN_API_KEY }}</code> and <code>${{ secrets.POSTMAN_WORKSPACE_ID }}</code> .</p>
<h3 id="heading-checkout-the-repository">Checkout the repository</h3>
<p>This first step checks out the repository. In this example (and probably in most cases) the files to process are part of the repository, therefore the checkout step makes sure the workflow can access them.</p>
<h3 id="heading-generate-postman-json-file">Generate Postman JSON file</h3>
<p>The second step is probably the most interesting one. From the OpenAPI file, it generates a Postman collection in JSON format, according to the <a target="_blank" href="https://schema.postman.com/collection/json/v2.1.0/draft-07/docs/index.html">Postman JSON format v2.1.0</a>.</p>
<p>This JSON generation is performed using the <a target="_blank" href="https://github.com/OpenAPITools/openapi-generator">OpenAPI Generator</a>, a popular open-source project that can generate code (in many different languages, client and server-side) starting from an OpenAPI specification.</p>
<p>In a nutshell:</p>
<ul>
<li><p>generates code from an OpenAPI file</p>
</li>
<li><p>supports 100+ languages</p>
</li>
<li><p>can be run from CLI, Docker or Java jar</p>
</li>
<li><p>open-source and extendible</p>
</li>
</ul>
<p>Check out my other <a target="_blank" href="https://medium.com/geekculture/from-api-specifications-to-code-with-openapi-76d13c12203b">blog</a> if you are interested in more details and samples.</p>
<h4 id="heading-postman-openapi-generator">Postman OpenAPI Generator</h4>
<p>Thankfully, the OpenAPI Generator supports also the <a target="_blank" href="https://github.com/OpenAPITools/openapi-generator/blob/master/docs/generators/postman.md">Postman format</a>, which I created and <a target="_blank" href="https://github.com/OpenAPITools/openapi-generator/pull/15294">contributed</a> 😃 to the project some time ago.</p>
<p>During the generation, the following happens:</p>
<ul>
<li><p>each endpoint in the OpenAPI specification becomes a folder in the collection</p>
</li>
<li><p>each request example becomes a Postman request in the collection</p>
</li>
<li><p>security schemes (API key, basic authentication) are configured in the collection</p>
</li>
<li><p>any placeholder in the JSON request example (i.e. <code>{{MY_VAR}}</code>) is defined as a collection variable</p>
</li>
<li><p>optionally path parameters can also be defined as collection variables</p>
</li>
</ul>
<p>Using the <a target="_blank" href="https://github.com/addnab/docker-run-action">Docker Run Action</a> we can run the OpenAPI Generator Docker image as part of the GitHub workflow and create the <code>postman.json</code> file.</p>
<pre><code class="lang-bash">- name: Generate postman.json    
  uses: addnab/docker-run-action@v3
  with:
    image: openapitools/openapi-generator-cli
    options: -v <span class="hljs-variable">${{ github.workspace }</span>}:/<span class="hljs-built_in">local</span>
    run: |
      <span class="hljs-built_in">echo</span> <span class="hljs-string">"Generate postman.json from <span class="hljs-variable">${{ github.event.inputs.file }</span>}"</span>
      /usr/<span class="hljs-built_in">local</span>/bin/docker-entrypoint.sh generate -i /<span class="hljs-built_in">local</span>/<span class="hljs-variable">${{ github.event.inputs.file }</span>} -g postman-collection -o /<span class="hljs-built_in">local</span>/out
</code></pre>
<p>Interesting to note above:</p>
<p><code>-i</code> indicates the path to the OpenAPI file</p>
<p><code>-g</code> defines which generator should run (<code>postman-collection</code> )</p>
<p><code>-o</code> sets the location of the generated JSON file</p>
<h4 id="heading-push-to-postman">Push to Postman</h4>
<p>The final step is accomplished using the <a target="_blank" href="https://github.com/marketplace/actions/push-to-postman">Push To Postman</a> GitHub action.</p>
<p>The action pushes <code>postman.json</code> files to Postman, creating or updating collections.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*GvlmAQuHd7SDfQ4AMtBnIw.png" alt /></p>
<p>Push to Postman action on GitHub Action marketplace — image by author</p>
<p>We will use the <code>createOrUpdate</code> goal so we can cover both create and update, without worrying if the collection already exists.</p>
<pre><code class="lang-bash">- name: Push to Postman    
        uses: gcatanese/push-to-postman-action@main
        with:
          goal: createOrUpdate
          postman-key: <span class="hljs-variable">${{ secrets.POSTMAN_API_KEY }</span>}
          postman-file: <span class="hljs-variable">${{ github.workspace }</span>}/out/postman.json
          workspace-id: <span class="hljs-variable">${{ secrets.POSTMAN_WORKSPACE_ID }</span>}
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>The article has covered how leading technologies, like OpenAPI and Postman, can be used together to streamline development workflows and ensure consistency between documentation and implementation.</p>
<p>Thanks to GitHub CI capabilities, this workflow can be automated, resulting in a dual benefit: it boosts developer productivity on the one hand and enhances the overall API consumer experience on the other.</p>
<p>Furthermore, there are additional scenarios worth exploring. For instance, automating the validation and testing of the API by executing the auto-generated Postman collection test cases.</p>
<p>Stay tuned for emerging tools and evolving best practices in the dynamic API ecosystem. Continuously iterating and refining your processes is the key to delivering outstanding APIs.</p>
]]></content:encoded></item><item><title><![CDATA[Testcontainers with OpenAPI]]></title><description><![CDATA[API integration testing with a contract-driven mock server]]></description><link>https://beppecatanese.hashnode.dev/testcontainers-with-openapi</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/testcontainers-with-openapi</guid><category><![CDATA[Testcontainers]]></category><category><![CDATA[OpenApi]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Sat, 22 Jul 2023 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/HpMihL323k0/upload/9e49724475479f23de65d4ad880fcac5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://testcontainers.com/">Testcontainers</a> is an open-source multi-language framework that has revolutionised integration testing by leveraging containerisation.</p>
<p>The concept is simple yet powerful: developers define and spin up Docker containers directly from the test code. These containers serve as replicas of the dependencies utilised by the application, creating an effective environment for running integration tests.</p>
<p>Testcontainers offers an extensive selection of <a target="_blank" href="https://testcontainers.com/modules/">pre-configured containers</a>, such as databases, message queues, and web servers. Additionally, it offers the flexibility to create <strong>new containers on the fly</strong>. This is a remarkable feature: developers can mock any dependency they require, including APIs under development.</p>
<p>And this is how I created a <a target="_blank" href="https://github.com/gcatanese/openapi-testcontainers">Testcontainer OpenAPI extension</a>.</p>
<blockquote>
<p>In this article: create a Testcontainer from an OpenAPI file, execute the integration testing leveraging the API contract, follow a step-by-step guide on how to test your API</p>
</blockquote>
<p><em>Check out</em> <a target="_blank" href="https://medium.com/geekculture/contract-testing-with-openapi-42267098ddc7"><em>Contract Testing with OpenAPI</em></a> <em>to understand the challenges and solutions of Contract Testing with the OpenAPI standard.</em></p>
<p><img src="https://cdn-images-1.medium.com/max/1600/0*DivCNlTIcGrzURmE" alt /></p>
<p>Photo by <a target="_blank" href="https://unsplash.com/@glencarrie?utm_source=medium&amp;utm_medium=referral">Glen Carrie</a> on <a target="_blank" href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></p>
<h3 id="heading-intro-to-testcontainers">Intro to Testcontainers</h3>
<p>If you haven’t done it yet, head to the <a target="_blank" href="https://java.testcontainers.org/quickstart/junit_5_quickstart/">Quickstart example</a> and try it out.</p>
<p>Testcontainers seamlessly integrate with the unit testing framework (JUnit for Java, Testing package for Go, etc..) of your choice. During the execution of the tests, the dependencies (i.e. database, cache, queues) required by your application are loaded by Testcontainers.</p>
<p>Testcontainers require a Docker runtime.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*kwaxQsEIVaO2XlJ0n6_blQ.png" alt /></p>
<p>Testing with Testcontainers — image by author</p>
<h3 id="heading-contract-testing-with-openapi">Contract testing with OpenAPI</h3>
<p>In my previous <a target="_blank" href="https://medium.com/geekculture/contract-testing-with-openapi-42267098ddc7">blog</a>, I have discussed the challenges (and options) of implementing contract testing with <a target="_blank" href="https://www.openapis.org/">OpenAPI</a>.</p>
<p>In a nutshell, the idea is to define the request-response interactions <strong>inside the OpenAPI file</strong>, the contract of your API. OpenAPI does not offer (yet) a native method for establishing those interactions, therefore we need to find a workaround: defining custom tags or adopting strict naming conventions.</p>
<p>Once this is solved, we can create an API mock server that implements those expectations. This mock server is going to be our Testcontainer.</p>
<h3 id="heading-use-cases">Use cases</h3>
<p>An API Tescontainers module can serve 2 use cases.</p>
<p><strong>API SDK development</strong></p>
<p>API SDKs are valuable tools that help developers integrate APIs without the need to implement the REST calls and all other aspects of the protocol. Adyen, for example, provides <a target="_blank" href="https://www.adyen.com/blog/adyen-api-libraries">open-source libraries</a> to build better integrations.</p>
<p>If you’re familiar with SDK development, you know that integration testing is critical to verify the following:</p>
<ul>
<li><p>the SDK code invokes the API endpoints</p>
</li>
<li><p>request payloads are built correctly</p>
</li>
<li><p>JSON responses are properly deserialized</p>
</li>
<li><p>headers are set accordingly</p>
</li>
</ul>
<p>Writing integration tests that invoke directly the API (on a test server) is always an option, but far from ideal. It is slow, and unpredictable (think of a network problem, server maintenance or a re-deployment of the service) and might have side effects (i.e. modify data during a POST request).</p>
<p><strong>Mock 3rd party API</strong></p>
<p>In many projects, developers consume <strong>3rd party APIs</strong>. However, directly invoking these APIs during integration testing can be tricky. Factors such as latency, availability, and changes in behaviour can lead to unreliable integration tests.</p>
<p><strong>OpenAPI Testcontainers to the rescue</strong></p>
<p>In both scenarios Testcontainers takes the pain away: the API runs in a Docker container, either locally or in a CI, creating an accurate replica of the production environment where integration tests are fast(er) and reliable.</p>
<p>It also gives you control over the test scenario: unlike the “real” API, it is possible to define specific scenarios and simulate various responses, error conditions, or edge cases.</p>
<h3 id="heading-openapi-mock-server-container">OpenAPI mock server container</h3>
<p>The generation of the mock server is accomplished using the <a target="_blank" href="https://github.com/OpenAPITools/openapi-generator">OpenAPI generator</a>. This popular open-source project allows the <a target="_blank" href="https://medium.com/geekculture/from-api-specifications-to-code-with-openapi-76d13c12203b">generation of code</a>, documentation and tools starting from an OpenAPI file.</p>
<p>Leveraging the OpenAPI generator and creating a new specific generator (that can determine the request-response interactions — as mentioned above) the API server-side code is generated and packaged in a Docker image.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/0*ioFwKlj1Ib3Pgk2A" alt /></p>
<p>Photo by <a target="_blank" href="https://unsplash.com/fr/@danielkcheung?utm_source=medium&amp;utm_medium=referral">Daniel K Cheung</a> on <a target="_blank" href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></p>
<h3 id="heading-getting-started">Getting started</h3>
<p>Check out the OpenAPI Testcontainers <a target="_blank" href="https://github.com/gcatanese/openapi-testcontainers-demo">demo</a>. It includes a sample Java project that shows all you need to do:</p>
<ul>
<li><p>create a multi-stage Dockerfile</p>
</li>
<li><p>write the integration tests</p>
</li>
</ul>
<p>The project is a sample SDK for using a User Management API: the UserService class provides a few methods that wrap the API calls (i.e. GET <a target="_blank" href="https://api.example.com/svc/users/%7Bid%7D%29"><code>https://api.example.com/svc/users/{id}</code>)</a>. The integration tests start a container hosting the API mock server and validate that the SDK methods can invoke the server-side API.</p>
<h4 id="heading-docker-file">Docker file</h4>
<p>The Docker file defines the container that the integration tests will interact with. This approach takes advantage of the “<a target="_blank" href="https://java.testcontainers.org/features/creating_images/">Creating images</a> on the fly” feature of Testcontainers.</p>
<p>There are 3 steps to consider:</p>
<ol>
<li><p><strong>Setup</strong>: install the OpenAPI generator</p>
</li>
<li><p><strong>Make</strong>: generate the API server-side implementation</p>
</li>
<li><p><strong>Package</strong>: build a minimal Docker image</p>
</li>
</ol>
<p>Using a Docker multi-stage build the process becomes more efficient, resulting in a smaller footprint for the final image.</p>
<p><strong>Setup</strong></p>
<p>The first step is already provided in the base image (<a target="_blank" href="https://hub.docker.com/repository/docker/gcatanese/openapi-native-mock-server">gcatanese/openapi-native-mock-server</a>) by the <a target="_blank" href="https://github.com/gcatanese/openapi-native-mock-server">OpenAPI Native Mock Server</a>. This includes everything you need (JDK, OpenAPI Generator client) to run the OpenAPI generator.</p>
<p>Onto task 2, the most interesting one.</p>
<p><strong>Make</strong></p>
<p>This step generates the server-side code of the API. Using the OpenAPI Generator it creates a <strong>Go server</strong> that implements all endpoints of the API contract.</p>
<blockquote>
<p><strong>Note</strong>: the Go server runs in Docker therefore it doesn’t matter which language or stack you are using (as long as it is supported by Testcontainers). The demo application, for example, is in Java.</p>
</blockquote>
<p>By leveraging the predefined request-response interactions, the API makes sure that for any given request, the expected response will be returned. In cases where a request does not match any of the predefined responses, a default JSON payload is generated to ensure that there is always a response available.</p>
<p>During this step, the OpenAPI file must be available and passed to the Docker build.</p>
<p><strong>Package</strong></p>
<p>The last step is the creation of a <strong>minimal Docker image</strong>, starting from a “scratch” image.</p>
<p>In the context of Docker, a “scratch” image refers to an empty base image. It is a special image, provided by Docker, that contains no files. When using the scratch image, you cannot rely on any pre-existing operating system or runtime to execute your application.</p>
<p>By leveraging Go static binary compilation, we can build a self-contained binary executable and copy it into the scratch image. The result is an extremely lightweight image (~15MB in this Sample app) that contains just the API server, highly convenient in the context of integration testing.</p>
<pre><code class="lang-bash">FROM gcatanese/openapi-native-mock-server

<span class="hljs-comment"># pass OpenAPI file</span>
ADD openapi.yaml /openapi/openapi.yaml
<span class="hljs-comment"># codegen</span>
RUN java -cp /openapi/bin/openapi-native-mock-server.jar:/openapi/bin/openapi-generator-cli.jar \
  org.openapitools.codegen.OpenAPIGenerator generate -g com.tweesky.cloudtools.codegen.NativeMockServerCodegen \
   -i /openapi/openapi.yaml -o /openapi/go-server

<span class="hljs-comment"># build Go executable</span>
FROM golang:1.19-alpine3.15
COPY --from=0 /openapi/go-server ./go-server

WORKDIR /go/go-server
RUN go mod tidy

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /build .

<span class="hljs-comment"># build minimal image</span>
FROM scratch AS runtime
<span class="hljs-comment"># copy executable from previous stage</span>
COPY --from=1 /build .

EXPOSE 8080
ENTRYPOINT [<span class="hljs-string">"./build"</span>]
</code></pre>
<h4 id="heading-write-the-tests">Write the tests</h4>
<p>Import the Testcontainers dependency (Maven or Gradle) and mark the tests with the <code>@Testcontainers</code> annotation.</p>
<pre><code class="lang-bash">@Testcontainers
public class UserServiceTest {
</code></pre>
<p>Next, define the <code>@ClassRule</code> : this is the <a target="_blank" href="https://junit.org/junit4/javadoc/4.12/org/junit/ClassRule.html">JUnit rule</a> that manages the container at class-level and therefore shared across all tests in the class. The <code>ClassRule</code> starts the container before any test in the class is executed and stops it when they are all completed.</p>
<p>Here is where you define the OpenAPI file that will be used to generate the API server-side code.</p>
<pre><code class="lang-bash">private final static String OPENAPI_FILE = <span class="hljs-string">"src/test/resources/openapi.yaml"</span>;    
private final static boolean DELETE_ON_EXIT = <span class="hljs-literal">false</span>;

@ClassRule
public static GenericContainer container = new GenericContainer(
   new ImageFromDockerfile(<span class="hljs-string">"my-test-cont"</span>, DELETE_ON_EXIT)
      .withFileFromFile(<span class="hljs-string">"openapi.yaml"</span>, new File(OPENAPI_FILE))
      .withFileFromFile(<span class="hljs-string">"Dockerfile"</span>, new File(<span class="hljs-string">"Dockerfile"</span>))
    )
    .withExposedPorts(8080);
</code></pre>
<p>A few important remarks:</p>
<ul>
<li><p>the OpenAPI file must be in the Dockerfile build context: a good place is with the test resources (<code>src/test/resources</code>)</p>
</li>
<li><p>setting the <code>deleteOnExit</code> flag to <code>false</code> doesn’t delete the container when the JVM exits, so that it is already built and ready when we run the tests the next time</p>
</li>
<li><p>only when the OpenAPI file changes the container is rebuilt</p>
</li>
</ul>
<p><strong>POST tests</strong></p>
<p>Finally, we write our tests. No surprises here but it is interesting to look at the scenario we test. In this first test, we verify a successful GET user.</p>
<pre><code class="lang-bash">// <span class="hljs-built_in">test</span> successful get user
@Test
public void getUser() throws Exception {
  User user = userService.get(<span class="hljs-string">"usr0001"</span>);

  assertEquals(<span class="hljs-string">"usr0001"</span>, user.getId());
  assertEquals(<span class="hljs-string">"Alan"</span>, user.getFirstName());
}
</code></pre>
<p>The <code>UserService.get</code> method, given the id <code>usr0001</code> , returns a User object with the expected ID and first name. This expected response is defined in the OpenAPI file.</p>
<p>In the second test, we check the scenario when the user is not found.</p>
<pre><code class="lang-bash">@Test(expected = RuntimeException.class)
public void userNotFound() throws Exception {
  User user = userService.get(<span class="hljs-string">"usr9999"</span>);
}
</code></pre>
<p>Again, the OpenAPI file defines this interaction (return 404 when id is <code>usr9999</code> ) and the test confirms that the SDK throws an exception.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Testcontainers make integration testing easy.</p>
<p>Using the OpenAPI extension I have shown how to create a container starting from an OpenAPI specification. The API server-side code is generated with OpenAPI Generator and packaged in a lightweight Docker image.</p>
<p>The Getting Started guide presents a step-by-step tutorial covering the setup, including the creation of the Docker file, and writing and executing the tests.</p>
<p>A sample demo also is provided to show Testcontainers with OpenAPI in action.</p>
]]></content:encoded></item><item><title><![CDATA[Contract Testing with OpenAPI]]></title><description><![CDATA[Wait, is that really possible?]]></description><link>https://beppecatanese.hashnode.dev/contract-testing-with-openapi</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/contract-testing-with-openapi</guid><category><![CDATA[OpenApi]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Testing]]></category><category><![CDATA[contract-testing]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Thu, 01 Jun 2023 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Cecb0_8Hx-o/upload/e00b3beca9d979ab4b053538a74b8d7a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>» Try out the <a target="_blank" href="https://github.com/gcatanese/openapi-native-mock-server">OpenAPI Native Mock Server</a></p>
<p>Contract testing has emerged as a trending topic for developers and teams working with APIs. There is already a <a target="_blank" href="https://www.headspin.io/blog/the-testing-pyramid-simplified-for-one-and-all">pyramid</a> of testing layers, so do we need another one? What is special about it, and what is the value?</p>
<p>But most importantly, from my OpenAPI specification, can I implement contract testing?</p>
<blockquote>
<p>In this article: let’s talk contract testing with OpenAPI. Is OpenAPI “ready” for contract testing? What are the options, challenges and opportunities?</p>
</blockquote>
<p>The question at hand is whether it is possible to implement contract testing using an OpenAPI file. Let me answer this: the answer is no. However, if you continue reading, I will elaborate on the limitations and explore options to address them. 😎</p>
<blockquote>
<p>Check out also <a target="_blank" href="https://beppecatanese.hashnode.dev/testcontainers-with-openapi">Testcontainers with OpenAPI</a> to see Contract Testing in action with TestContainers.</p>
</blockquote>
<hr />
<h3 id="heading-what-is-contract-testing">What is Contract Testing</h3>
<p>There is plenty of literature on contract testing, thanks to various breakthrough tools, with <a target="_blank" href="https://docs.pact.io/">Pact</a> as the leading example. For a clear and simple “getting started,” you can start from <a target="_blank" href="https://www.blazemeter.com/blog/contract-testing">here</a>.</p>
<p>A good definition of contract testing is a testing technique that makes sure the <strong>API consumer and provider meet each other’s expectations</strong>.</p>
<p>In (my) even simpler words:</p>
<blockquote>
<p>“as I consumer I want to send a request that will receive a given response”.</p>
</blockquote>
<p>Like every contract, this commitment must apply until there is a new contract in place. It must be clear to the consumer and honoured by the provider. It should be verifiable by machines (automation).</p>
<h3 id="heading-openapi-to-contract-testing">OpenAPI to Contract Testing</h3>
<p>For developers embracing the OpenAPI standard, the obvious question is: how can I leverage my specifications (where I have invested time and effort)? At the end of the day, I have already designed my endpoints and defined parameters, requests and responses. I have also (right?) provided several examples to make the specifications clearer.</p>
<h4 id="heading-the-missing-link">The missing link</h4>
<p>Unfortunately, the OpenAPI standard yet does not establish a unique relation (a.k.a interaction) between a request and its response. This prevents the spec designers from defining interaction flows that are the essence of contract testing. Let’s have a look:</p>
<pre><code class="lang-bash">  /users:
    post:
      summary: Create user
      requestBody:
        content:
          application/json:
            examples:
              example-user-eur:
                <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/create-user-eur'</span>
              example-user-us:
                <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/create-user-us'</span>
      responses:
        <span class="hljs-string">'200'</span>:
          content:
            application/json:
              examples:
                create-user-1:
                  <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/response-ex'</span>
        <span class="hljs-string">'422'</span>:
          content:
            application/json:
              examples:
                validation-error:
                  <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/user-error-422'</span>
</code></pre>
<p>The YAML extract above is nice and tidy, but it doesn't indicate which request example belongs to which response. OpenAPI 4.0 (still in the brainstorming phase) has initiated a <a target="_blank" href="https://github.com/OAI/OpenAPI-Specification/discussions/2930#discussioncomment-2797695">discussion</a> about it, so that’s promising but looking a long way off.</p>
<h3 id="heading-naming-convention-approach">Naming convention approach</h3>
<p>One possible approach to this problem is to establish your conventions. In this case, you would name your examples using a predefined <strong>prefix</strong>.</p>
<p>This works when using <code>$ref</code> to point to re-usable components: the request example <code>create-user-us</code> is associated (1:1) with the response example <code>create-user-us-200</code> . The examples share the same prefix while the response appends the status code.</p>
<pre><code class="lang-bash">/users:
    post:
      summary: Create user
      requestBody:
        content:
          application/json:
            examples:
              example-user-eur:
                <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/create-user-eur'</span>
              example-user-us:
                <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/create-user-us'</span>
              example-user-invalid:
                <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/user-error'</span>      
    responses:
        <span class="hljs-string">'200'</span>:
          content:
            application/json:
              examples:
                create-user-1:
                  <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/create-user-eur-200'</span>
                create-user-2:
                  <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/create-user-us-200'</span>        
        <span class="hljs-string">'422'</span>:
          content:
            application/json:
              examples:
                validation-error:
                  <span class="hljs-variable">$ref</span>: <span class="hljs-string">'#/components/examples/user-error-422'</span>
</code></pre>
<p>Summarising in a Given-When-Then style:</p>
<ul>
<li><p>given <code>create-user-eur</code> when <code>POST /users</code> then <code>create-user-eur-200</code></p>
</li>
<li><p>given <code>create-user-us</code> when <code>POST /users</code> then <code>create-user-us-200</code></p>
</li>
<li><p>given <code>user-error</code> when <code>POST /users</code> then<code>user-error-422</code></p>
</li>
</ul>
<h4 id="heading-pros-and-cons">Pros and cons</h4>
<p>There is no significant complexity to implementing this. It only requires a diligent approach to make sure the naming is defined and correctly applied.</p>
<p>On the other side, there are a few limitations:</p>
<ul>
<li><p>it only works with <code>$ref</code> (references to components) and therefore not helpful for requests without a body (schema)</p>
</li>
<li><p>linting (validation) becomes complicated (involving custom implementation with partial text matching)</p>
</li>
<li><p>it cannot link multiple requests to the same response, for example, a shared <code>404</code> error response</p>
</li>
</ul>
<h3 id="heading-custom-extension-approach">Custom extension approach</h3>
<p>Another way is to leverage the <a target="_blank" href="https://swagger.io/docs/specification/openapi-extensions/">OpenAPI extensions</a>. This works in this way: define a custom property <code>x-contract-id</code> that tags the interaction between a request and a response.</p>
<pre><code class="lang-bash">  ...
  examples:
    create-user-eur:
      summary: Create user example
      x-contract-id: post-user-eur
      value:
        firstname: Beppe
        lastname: Catanese
    new-user:
      summary: Create user example response
      x-contract-id: post-user-eur
      value:
        id: 00001
        createdOn: 2023-05-31T02:55:00.1Z
</code></pre>
<p>Summarising in a Given-When-Then style:</p>
<ul>
<li>given <code>create-user-eur</code> when <code>POST /users</code> then <code>new-user</code></li>
</ul>
<p>As you notice there is no constraint on naming the examples.</p>
<h4 id="heading-pros-and-cons-1">Pros and cons</h4>
<p>This works, in my opinion, a lot better. It doesn’t rely on strict naming patterns and it can use the same <code>x-contract-id</code> multiple times (if necessary). I find it convenient that the matching interactions can be spotted more easily by looking or searching in the <code>examples</code> section of the specification.</p>
<p>Another advantage is that, unlike the naming approach, it can be used with parameters or inline examples. This is how we could define a response for a GET request (without a body):</p>
<pre><code class="lang-bash">parameters:
  - description: User identifier
    name: id
    <span class="hljs-keyword">in</span>: path
    required: <span class="hljs-literal">true</span>
    schema:
      <span class="hljs-built_in">type</span>: string
    examples:
      get-transaction:
        x-contract-id: get-user-example-1
        value: 1
</code></pre>
<p>The downside is the introduction of an extension. As with any customisation, it introduces a new non-standard element that needs to be dealt with accordingly, typically requiring some extra work by the consuming tool or application.</p>
<h3 id="heading-final-thoughts">Final thoughts</h3>
<p>Despite the current limitations in supporting contract testing directly from an OpenAPI file, exploiting naming conventions or leveraging extensions can help overcome this.</p>
<p>Being able to define the <strong>interaction flows within the OpenAPI specification</strong> will give the API designers an additional element to describe the API behaviour. It will also create opportunities for OpenAPI-driven mock servers (where requests and responses are defined within the examples), Postman collection testing and improving support for contract testing tools that today need to define (or record) those interactions.</p>
<p>My preferred solution is the custom extension (for the reasons explained above) and I will be building a POC very soon. Stay tuned.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/0*PRZ5YdMiEIj-1bvN" alt /></p>
<p>Photo by <a target="_blank" href="https://unsplash.com/@srz?utm_source=medium&amp;utm_medium=referral">sydney Rae</a> on <a target="_blank" href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></p>
<p>Are you facing similar challenges? Did you find other solutions? I am looking forward to hearing your take on this and starting a debate.</p>
]]></content:encoded></item><item><title><![CDATA[Validating API requests and responses]]></title><description><![CDATA[Shift left with Postman and OpenAPI specification]]></description><link>https://beppecatanese.hashnode.dev/validating-api-requests-and-responses</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/validating-api-requests-and-responses</guid><category><![CDATA[Postman]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Tue, 31 Jan 2023 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/hPcF0UCpNhs/upload/65e81d95a5fa67ef5acb6cb4d85e7aad.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There are plenty of excellent and well-established tools that help design, create and validate an OpenAPI specification. But surely it is (at least) as critical to ensuring that the <strong>API contracts</strong> are honoured by the API we are developing.</p>
<blockquote>
<p>In this article: find out how you can <strong>use Postman to validate the requests and responses,</strong> catch inconsistencies early, try out the OpenAPI Request Response Validator.</p>
</blockquote>
<h3 id="heading-what-we-are-going-to-do">What we are going to do</h3>
<p>The goal is to validate the <strong>API behaviour at runtime</strong>, so we are going to pass headers, request and response bodies to the validator and verify the API “does what it says”, according to its OpenAPI specification.</p>
<p>There are several components involved:</p>
<ul>
<li><p>the OpenAPI file (obviously)</p>
</li>
<li><p>your REST API (running somewhere)</p>
</li>
<li><p>Postman to invoke the API endpoints</p>
</li>
<li><p>the Validator tool running on localhost</p>
</li>
</ul>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*gqXCuAtlBeltYrFDaR1x9A.png" alt="Diagram illustrating the interaction between Postman, a REST API, and an OpenAPI validator. The Postman icon points to a REST API with OpenAPI specs and an OpenAPI Validator, linked via &quot;http://localhost:8080&quot;. The validator shows indicators for &quot;PASS&quot; and &quot;FAIL&quot;." class="image--center mx-auto" /></p>
<h3 id="heading-why-postman">Why Postman</h3>
<p>The OpenAPI Validator is a standalone application (see later) and could be used in different ways (CI, integration testing, API gateway), but the Postman integration is powerful as it helps developers validate the API locally (<strong>shift-left</strong>), catch issues early, fix them before everyone finds out 😁.</p>
<p>Postman <a target="_blank" href="https://learning.postman.com/docs/writing-scripts/test-scripts/">Tests</a> allow writing test scripts that <strong>run after the execution</strong> of the request: we are going to use this feature to create a script that validates the interaction with the API, using an assertion to validate the expected result.</p>
<p>While a Test can be defined for each request, it is also possible (and extremely useful in this case) to <strong>create the Test script at the Collection level</strong>. You have already guessed, didn’t you? Doing this the script will run after every request in the collection.</p>
<h3 id="heading-collection-test-script">Collection Test Script</h3>
<p>In the Collection Tests add the snippet below.</p>
<pre><code class="lang-bash">// define object
openapiRequestResponseValidation = {
    // define <span class="hljs-keyword">function</span>
    validate: <span class="hljs-keyword">function</span>(pm) {

        const postRequest = {
            url: <span class="hljs-string">'http://localhost:8080/validate'</span>,
            method: <span class="hljs-string">'POST'</span>,
            header: {<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>},
            body: {
            mode: <span class="hljs-string">'raw'</span>,
            raw: JSON.stringify({ 
                method: pm.request.method, 
                path: pm.request.url.getPath(),
                headers: pm.request.headers,
                requestAsJson: (pm.request.body != <span class="hljs-string">""</span>) ? pm.request.body.raw : null,
                responseAsJson: pm.response.text(),
                statusCode: pm.response.code
                })
            }
        };

        pm.sendRequest(postRequest, (error, response) =&gt; {
            <span class="hljs-keyword">if</span>(error != undefined) {
                pm.expect.fail(<span class="hljs-string">'Unexpected error '</span> + error);
            } <span class="hljs-keyword">else</span> {
                var data = response.json();

                <span class="hljs-keyword">if</span>(data.valid == <span class="hljs-literal">false</span>) {
                    console.log(data.errors);
                }

                pm.test(<span class="hljs-string">"OpenAPI validation"</span>, () =&gt; {
                    pm.expect(data.valid, <span class="hljs-string">"Invalid request/response (check Console)"</span>).to.equal(<span class="hljs-literal">true</span>);
                });

            }
        });  
    }

};

// invoke <span class="hljs-keyword">function</span>
openapiRequestResponseValidation.validate(pm);
</code></pre>
<p>Let’s break down what happens:</p>
<ul>
<li><p>first, create the object <code>openapiRequestResponseValidation</code> that includes a single function <code>validate</code> .</p>
</li>
<li><p>the function <code>validate</code> performs 3 steps: it collects all data we need (headers, request, response, HTTP status), sends a POST request to the Validator and verifies the outcome.</p>
</li>
</ul>
<p>If it goes smoothly the test passes and is marked as green.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*Joq9kxtxDHZMtP4iV4nMww.png" alt="Test passing and marked as green" /></p>
<p>OpenAPI validation</p>
<h3 id="heading-openapi-request-response-validator">OpenAPI Request Response Validator</h3>
<p>The <a target="_blank" href="https://github.com/gcatanese/openapi-request-response-validation">openapi-request-response-validator</a> is a SpringBoot application with a REST controller to allow Postman scripts (or other clients) to send the payload to validate. The OpenAPI file can be supplied at startup.</p>
<p>The outcome of the validation (together with the list of errors — if any) is returned to Postman (displayed in the Postman console) and logged by the application.</p>
<h4 id="heading-run-with-java">Run with Java</h4>
<p>Copy/rename your OpenAPI specs to <code>openapi/openapi.yaml</code> or <code>openapi/openapi.json</code> and start the application:</p>
<pre><code class="lang-bash">mvn spring-boot:run
</code></pre>
<p>If needed you can customise the location of the OpenAPI file</p>
<pre><code class="lang-bash">mvn spring-boot:run 
  -Dspring-boot.run.arguments=<span class="hljs-string">"--inputSpecs=/path/to/myopenapi.yaml"</span>
</code></pre>
<h4 id="heading-run-with-docker">Run with Docker</h4>
<p>You can also run it on Docker</p>
<pre><code class="lang-bash">
<span class="hljs-comment"># run using default openapi/openapi.yaml or openapi/openapi.json</span>
docker run -v $(<span class="hljs-built_in">pwd</span>):/openapi -it --rm \
  --name openapi-request-response-validation \
    gcatanese/openapi-request-response-validation
</code></pre>
<p>Once the validator is running you can crack on: run the Postman requests and check the Test Results (in case of errors).</p>
<h3 id="heading-final-remarks">Final remarks</h3>
<p><strong>OpenAPI examples</strong></p>
<p>A little bonus is when your Postman collection uses (i.e. request body) the examples included in the OpenAPI file. The validation can then confirm those examples match the OpenAPI specs. We all know the API evolves and the specs change but the examples can be overlooked.</p>
<p><strong>Business as usual</strong></p>
<p>The idea behind the tool is that developers can focus on creating the best API while the validation is performed in the background. Go on and develop, test and ship your API (the validator will not bother you if everything works as expected).</p>
<p><strong>API fails, validation doesn’t</strong></p>
<p>That's a perfectly valid scenario. API calls might fail (backend errors, business rules) but the OpenAPI contract is not broken. The response with the error should be documented in the OpenAPI file and will also be validated.</p>
]]></content:encoded></item><item><title><![CDATA[From API specifications to code with OpenAPI]]></title><description><![CDATA[Generating client and server source code]]></description><link>https://beppecatanese.hashnode.dev/from-api-specifications-to-code-with-openapi</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/from-api-specifications-to-code-with-openapi</guid><category><![CDATA[APIs]]></category><category><![CDATA[OpenApi]]></category><category><![CDATA[codegeneration]]></category><category><![CDATA[mustache]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Sun, 18 Dec 2022 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/CDpCbaOThwg/upload/e7f9751c8481d18b132c8ef74322acd3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The API economy is on fire 🔥🔥🔥</p>
<p>It has been on fire for years. Applications need to talk, systems must exchange data, and business processes require the implementation of sophisticated workflows composing existing services and functions.</p>
<p>Fortunately, the OpenAPI initiative is playing a key role in defining, through the vast jungle of applications and tools, an open standard.</p>
<blockquote>
<p>I<strong>n this article…</strong> discover how OpenAPI is essential to deliver Developer Experience in the API ecosystem, learn which OpenAPI tools can be adopted to generate source code, see a demo of client and server side code generation.</p>
</blockquote>
<h3 id="heading-openapi-and-openapi-tools-not-exactly-the-same">OpenAPI and OpenAPI Tools: not exactly the same</h3>
<h4 id="heading-openapi">OpenAPI</h4>
<p><a target="_blank" href="https://www.openapis.org/">OpenAPI</a> is the “Lingua Franca” in the API world. This is one of the best definitions you will find to understand the role the standard plays.</p>
<p>“Lingua Franca” was, back in the middle age, how countries and people, who spoke different languages, found a way to communicate for a very important reason: trading.</p>
<p>OpenAPI <strong>defines a common language</strong> (in a human and machine-readable format) that allows the different parties to understand each other.</p>
<p>A quick note about the history of OpenAPI: it started as Swagger (the 2 terms are used often interchangeably), created by the Wordnik team for again a very important reason: Developer Experience. The team, at that time, wanted to help developers understand and use APIs, therefore they created Swagger and paved the path for OpenAPI.</p>
<h4 id="heading-openapi-tools">OpenAPI Tools</h4>
<p><a target="_blank" href="https://github.com/OpenAPITools">OpenAPI Tools</a> is an initiative not affiliated with OpenAPI, but rather an umbrella of projects and tools built on top of the standard.</p>
<p>The main tools provided are:</p>
<ul>
<li><p>Code Generator: how to generate code from an OpenAPI specification</p>
</li>
<li><p>Validator: validation of an OpenAPI file to ensure it meets the organisation API style guide and standards</p>
</li>
<li><p>Diff: comparison between different versions of the same OpenAPI file to highlight what has changed</p>
</li>
</ul>
<h3 id="heading-code-generator">Code Generator</h3>
<p>The Code Generator is definitely the most popular of these tools and it has reached a wide adoption (14.6K Github stars).</p>
<p>The goal of the tool is, starting from a valid OpenAPI specification, to <strong>generate source code</strong>, either on the client or server side.</p>
<p>It supports 100+ languages and sometimes multiple frameworks for the same language (think of Java with support for Spring, RestEasy and Jersey).</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*8__371WYbEGPaz7QV8YvTw.png" alt="Rows of checkmark icons with the words: Client, Server, 100+ languages, Configuration, Documentation, CLI, Docker, Jar, Maven, Gradle." class="image--center mx-auto" /></p>
<p>OpenAPI Code Generator features  (Image by author)</p>
<p>The generator can also create configuration files (i.e. the Apache configuration file can be created from OpenAPI) and documentation in various formats (HTML, Markdown, etc…).</p>
<p>Finally, the tool can be used with its own CLI or through Docker. If you are in the Java world you are in luck: it is developed in Java so you can build it from the source and invoke the jar, or integrate the Maven or Gradle plugin.</p>
<h3 id="heading-the-adyen-way-of-api">The Adyen way of API</h3>
<p>Before we dive into the technical details of the code generation I would like to touch on why the OpenAPI standard is important at Adyen and the role of the OpenAPI Code Generator.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*txFuBWFCZ3NQqHq1KofNNA.png" alt="Flow diagram showing the process from source code to OpenAPI files. OpenAPI Generator converts source code into API-specs and API-explorer-content for internal use, leading to API Explorer. Open source Adyen-openapi goes to Swagger and Postman." class="image--center mx-auto" /></p>
<p>From Specs to Code  (Image by author)</p>
<p>The code base in the internal repositories is annotated (to describe endpoints, data models and attributes) and processed by the OpenAPI generator. The OpenAPI files are generated and published to <a target="_blank" href="https://github.com/Adyen/adyen-openapi">GitHub</a>.</p>
<p>The specs are now <strong>public and available to everyone</strong>. We have then identified 3 ways of consuming those:</p>
<ul>
<li><p>make them available to popular developer tools (Postman and SwaggerHub)</p>
</li>
<li><p>feed those to our own <a target="_blank" href="https://docs.adyen.com/api-explorer/">API Explorer</a>, an environment where all developers working with the Adyen platform can access the latest documentation, including examples and an interactive space to test requests and responses</p>
</li>
<li><p>generate the source code of the <a target="_blank" href="https://github.com/adyen">Adyen SDKs</a></p>
</li>
</ul>
<h4 id="heading-from-specs-to-go-client">From specs to Go client</h4>
<p>It is now time to see the OpenAPI Generator in action. We are going to create a Go client. Note how we set the language (<code>-g go</code>) and the destination folder (<code>-o tmp/gocodegen</code>).</p>
<pre><code class="lang-plaintext">openapi-generator-cli generate -i SampleProject.yaml \
-g go -p packageName=User -o tmp/gocodegen
</code></pre>
<p>The outcome is an initial implementation of a Go client that includes the code to invoke the endpoints, the model (mapping the request and response payloads) and some configuration code needed to set up the client and the connection details.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*ggoI65gws9lwp4UFmgrS0Q.png" alt="Go client in IntelliJ" class="image--center mx-auto" /></p>
<p>Go client in IntelliJ  ( image by author)</p>
<h4 id="heading-source-code-templates"><strong>Source code templates</strong></h4>
<p>The code generation works out of the box because the OpenAPI generator provides a <strong>default implementation of the source code templates</strong> (one for each language and framework combination). Those templates basically define how the specific code is going to look, from the method signature to the default body implementation, comments, and so on.</p>
<p>Check out my previous article if you want to know more about Mustache templates, the logic-less templating framework used by OpenAPI Tools.</p>
<p><a target="_blank" href="https://medium.com/geekculture/mustache-templates-with-openapi-specs-f24711c67dec"><strong>Mustache templates with OpenAPI specs</strong><br /><em>Best features of the OpenAPI code generation</em>medium.com</a></p>
<h4 id="heading-sdk-developer-workflow">SDK developer workflow</h4>
<p>The workflow of the SDK developer is different. The key aspect is that (part of) the code is generated with OpenAPI Generator.</p>
<p>After fetching and customising the default code templates the magic happens: the code is generated by the tool. This is followed by other development activities (integrating with the rest of the application, adding tests, etc..) until the library is ready to be released.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*YctpHgfb82IW_AlU7pWZ1Q.png" alt="Flowchart illustrating API development stages: Fetch, Customize, Generate, Develop, Release, leading to a new API version." class="image--center mx-auto" /></p>
<p>SDK workflow  (image by author)</p>
<h4 id="heading-scenario-1">Scenario 1</h4>
<p>After a quick team celebration, a new API version is released: boom! Not to worry: the developers grab the latest specs and regenerate the code, develop, test and ship again.</p>
<h4 id="heading-scenario-2">Scenario 2</h4>
<p>The new version of the API might require some changes to the templates, maybe there are new features that were not considered before. In this case, the developers first adjust the source code templates and then proceed with the steps discussed above.</p>
<h3 id="heading-from-specs-to-java-server-stubs">From specs to Java server stubs</h3>
<p>Let’s move on and generate the server-side code using Java and Springboot, in this case also customising the source code templates.</p>
<p>First step: fetch the default templates from the Github repository.</p>
<pre><code class="lang-plaintext">openapi-generator-cli author template -g spring -o tmp/myspringtemplate
</code></pre>
<p>The templates are now copied locally at <code>tmp/myspringtemplate</code> . Go on and edit them, for instance, open <code>api.mustache</code> and change the Java doc</p>
<pre><code class="lang-plaintext">
    /**
      custom note: generated for a demo
     * {{httpMethod}} {{{path}}}{{#summary}} : {{.}}{{/summary}}
    {{#notes}}
     * {{.}}
    {{/notes}}
</code></pre>
<p>Let’s also alter the generated body of the method, open <code>methodBody.mustache</code> and add some new code (for example we could check the API key in the header or something else).</p>
<pre><code class="lang-plaintext">{{^reactive}}
{{#examples}}
    {{#-first}}
            // check API key
            // ...
            {{#async}}
</code></pre>
<p>Onto the final step: kick off the code generation.</p>
<pre><code class="lang-plaintext">openapi-generator-cli generate -i SampleProject.yaml -g spring \
-p apiPackage=com.adyen.api -p modelPackage=com.adyen.model \
-p groupId=com.adyen -p artifactId=MySampleApp -p artifactVersion=v0.1 \
-p invokerPackage=com.adyen -p configPackage=com.adyen.configuration \
-t tmp/myspringtemplate -o tmp/javacodegen
</code></pre>
<p>There are several settings (in this example the Java project requires configuration like the package name, Maven attributes, etc…), but what it is important to note is that we want to <strong>use our custom templates</strong> (<code>-t tmp/myspringtemplate</code>), we select the <code>spring</code> generator and set the destination folder (<code>-o tmp/javacodegen</code>).</p>
<h3 id="heading-practices-and-challenges">Practices and challenges</h3>
<p>As we have seen the workflow and development lifecycle are different when adopting a specification-driven code generation. There are surely several benefits as long as good practices are adopted and challenges are managed.</p>
<h4 id="heading-generate-then-re-generate">Generate, then re-generate</h4>
<p>This is really crucial. Code should always be (re)generated from specifications and therefore <strong>avoid manual ad-hoc changes</strong>.</p>
<p>This can be achieved in 2 ways:</p>
<ul>
<li><p><strong>suitable templates</strong>: add to the templates the code you need so it will always be included during the generation</p>
</li>
<li><p><strong>good design</strong>: define a clear separation between the code that is (re)generated and the parts that cannot be (i.e. business logic, specific configurations, integration tests maybe). Think about different layers, components or classes.</p>
</li>
</ul>
<h4 id="heading-model-services-skip-files">Model, services, skip files</h4>
<p>It is definitely a good start to generating the model.</p>
<p>Mapping manually large JSON payloads to classes/structs is tedious and error-prone. Take advantage of the OpenAPI Generator and create the model automatically without forgetting or misspelling fields.</p>
<p>Next, generate the services (client calls or server stubs).</p>
<p>Skip what is not applicable to your project (i.e. some scripts that the generator might add) or the code you prefer to manage outside the automated process (for example sophisticated configuration code that is entangled with your existing application and frameworks). This is easily done by listing the files to skip in the <code>.openapi-generator-ignore</code> file.</p>
<h4 id="heading-templates-can-change">Templates can change</h4>
<p>The latest version of OpenAPI Generator finally has the feature or fix you have been waiting for. But this version is no longer compatible with the source code templates you customised years ago. This might involve significant refactoring.</p>
<p>My advice is to stay on top of things: keep upgrading the OpenAPI Generator as new versions are released and deal with the changes incrementally.</p>
<h3 id="heading-conclusions">Conclusions</h3>
<p>We are giving developers documentation, code snippets, examples and working code. But they want and need more and better.</p>
<p>Requirements change often, businesses must adapt fast and developers need the best tools and support.</p>
<p>OpenAPI and its ecosystem can help us deliver on those promises as long as we stick to a few principles:</p>
<ul>
<li><p><strong>discoverability</strong>: can the relevant information be found easily?</p>
</li>
<li><p><strong>simplicity</strong>: is the generated code clear and usable?</p>
</li>
<li><p><strong>consistency</strong>: are the documentation, examples, and SDKs reflecting accurately the content of the OpenAPI specifications?</p>
</li>
</ul>
<p>Developer Experience is a feeling developers have at a given time when using your API, tool or product, and therefore it will over time change. It requires ongoing investment and an open mindset: we are never done and there is always room for improvement.</p>
]]></content:encoded></item><item><title><![CDATA[Deploy Docker images on Fly.io free tier]]></title><description><![CDATA[Three different ways to deploy Docker images]]></description><link>https://beppecatanese.hashnode.dev/deploy-docker-images-on-flyio-free-tier</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/deploy-docker-images-on-flyio-free-tier</guid><category><![CDATA[Docker]]></category><category><![CDATA[Heroku]]></category><category><![CDATA[fly.io]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Tue, 20 Sep 2022 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/MS7KD9Ti7FQ/upload/51094e39e8f92050f5deaf8294d487b4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>In this article… Heroku drops the free tier, why Fly.io is a better platform, and the different ways to deploy your Dockerized applications on Fly.io.</p>
</blockquote>
<p>Heroku announced in August that the <a target="_blank" href="https://blog.heroku.com/next-chapter">free tier</a> of its application hosting and data services would end, and the company would focus only on (paying) mission-critical applications. Student, non-profit, and open-source programs should still be available (maybe newly redesigned), but the <strong>era of free hosting</strong> for prototypes and new startup ideas is over.</p>
<p>This is a bit of a bummer ☹️: just to be clear, I am a Heroku paying customer for some of my projects that reached a bit of interest (or at least I considered worth investing in). I found that model great: as a developer I start d<strong>eveloping and deploying at no cost</strong> to test my ideas, create beta projects, and learn through building. If and when I need something more (for example prevent the Dyno sleep (*) after 30 min inactivity) I go with “pay-as-you-go”: at that point, my app is already available, tested and fully working, therefore I am confident that this cost is a good investment.</p>
<p>This is now over.</p>
<p><em>(\</em>) Heroku web Dynos go on stand-by after 30 minutes without incoming HTTP requests. When a new request arrives the Dyno restarts).*</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*8fbIHzY7aGlwUnSMbAaj2g.png" alt /></p>
<p>Image by author</p>
<h3 id="heading-making-hosting-free-and-simple-flyio">Making hosting free and simple: Fly.io</h3>
<p><a target="_blank" href="https://fly.io/">Fly.io</a> is a free hosting platform founded in 2017 (initially to support the Javascript runtime) that has quickly become the new (better) Heroku.</p>
<p>There is support for many <a target="_blank" href="https://fly.io/docs/languages-and-frameworks/">frameworks</a>, a <a target="_blank" href="https://fly.io/docs/about/pricing/">free</a> tier (based on shared CPUs) and a top-notch developer experience.</p>
<p><strong>Start with the frameworks</strong>: the list of supported languages is exhaustive with guides and examples for each one, but what makes it awesome (and what this article will focus on) is the <a target="_blank" href="https://fly.io/docs/languages-and-frameworks/dockerfile/">Docker</a> support.</p>
<p><strong>Next the free tier</strong>: Fly.io gives you enough resources to run simple applications, eventually with the option to pay and scale up on demand. The free-tier already comes with a log viewer, metrics, the option to create SSL certificates for your custom domains, volumes to persist application state and <a target="_blank" href="https://fly.io/docs/reference/private-networking/">private networking</a> (apps can talk to each other — yes, privately).</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*DQRQhvszBsfrQwtRYyRXYw.png" alt /></p>
<p>Application metrics on Fly — Screenshot by author</p>
<p><strong>Now the developer experience</strong>. This is where Fly.io eclipses Heroku: concise documentation (straight to the point, no frills but enough details), a powerful CLI <code>flyctl</code> and an active <a target="_blank" href="https://community.fly.io/">community</a>.</p>
<p>Unlike Heroku on Fly.io secrets (ie tokens and passwords) are treated differently (one-way encryption) from environment variables (set in the <code>fly.toml</code> descriptor) and the application's internal port can be declared statically (no need to bind a dynamic port assigned by the platform).</p>
<p>The application never sleeps (unlike Heroku free Dynos) so it will always be responsive (or at least ready to process incoming requests).</p>
<h3 id="heading-docker-on-flyio">Docker on Fly.io</h3>
<p>There are different ways to deploy Docker images on Fly.io:</p>
<ul>
<li><p>use the Dockerfile builder</p>
</li>
<li><p>use an existing Docker image</p>
</li>
<li><p>push to Fly.io Docker Registry</p>
</li>
</ul>
<h4 id="heading-fly-docker-builder">Fly Docker Builder</h4>
<p>The default mechanism is to let Fly build the Docker image: you only need a Dockerfile and make sure there is no builder (ie no <code>[build]</code> tag) defined in the <code>fly.toml</code> .</p>
<p>This is indeed a nice approach (to be fair Heroku offers the same) as we let Fly do the hard work and we are sure that the created image is compatible with the Fly runtime (more on this later).</p>
<pre><code class="lang-bash"><span class="hljs-comment"># first time launch</span>
fly launch
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># (re)deploy existing app</span>
fly deploy
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># (re)deploy existing app with custom Dockerfile</span>
fly deploy --dockerfile myDockerfile
</code></pre>
<p>The remote builder also makes trivial the integration with CI/CD pipelines, for example on GitHub Actions with the <code>flyctl-actions</code> .</p>
<pre><code class="lang-bash">name: Deploy on fly.io
on:
  workflow_dispatch
<span class="hljs-built_in">jobs</span>:
  deploy:
    name: Deploy proxy
    runs-on: ubuntu-latest
    steps:
      <span class="hljs-comment"># check out repository and flyctl deploy</span>
      - uses: actions/checkout@v2
      - uses: superfly/flyctl-actions/setup-flyctl@master
      - run: flyctl deploy --app &lt;my_app_name&gt;
        env:
          FLY_API_TOKEN: <span class="hljs-variable">${{ secrets.FLY_API_TOKEN }</span>}
</code></pre>
<h4 id="heading-existing-docker-image">Existing Docker image</h4>
<p>Another way is to configure your Fly application to use an existing image: in the <code>fly.toml</code> file set the image location in the <code>[build]</code> section.</p>
<pre><code class="lang-bash">app = <span class="hljs-string">"myApp"</span>
kill_signal = <span class="hljs-string">"SIGINT"</span>
kill_timeout = 5
processes = []

[build]
  image = <span class="hljs-string">"repo/myImage:latest"</span>

[env]
  VAR=<span class="hljs-string">"myValue"</span>
</code></pre>
<p>When calling <code>flyctl deploy</code> the build step is skipped and the specified image is retrieved.</p>
<h4 id="heading-when-to-use-this">When to use this</h4>
<p>This might be convenient when the docker image is already created, maybe hardened and generated by a different team or pipeline.</p>
<h4 id="heading-the-catch">The catch</h4>
<p>Devs (like me!?) building the image on their Mac M1 need to carefully set the target platform. Fly, like Heroku and many others, require images running on AMD architecture, so the M1 ARM architecture will not work.</p>
<pre><code class="lang-bash">docker build --platform linux/amd64 -t repo/myApp:latest .
</code></pre>
<p><strong>Note</strong>: Images can be fetched by DockerHub or GitHub packages, but currently there is <strong>no support</strong> for fetching from private Docker registries.</p>
<h4 id="heading-push-to-flyio-docker-registry">Push to Fly.io Docker Registry</h4>
<p>The last option is to push the images directly into the Fly Docker Registry.</p>
<p>Authorise your account first</p>
<pre><code class="lang-bash">flyctl auth login
</code></pre>
<p>then tag an existing image (or build the image) and push</p>
<pre><code class="lang-bash">docker tag myImage registry.fly.io/myImage
</code></pre>
<pre><code class="lang-bash">docker push registry.fly.io/myImage
</code></pre>
<h4 id="heading-when-to-use-this-1">When to use this</h4>
<p>This can be considered when the docker image is already available but we don’t want it to be stored in any Docker Registry (i.e. DockerHub) aside Fly.io.</p>
<h3 id="heading-conclusions">Conclusions</h3>
<p>In this blog post, we have looked at different ways to deploy Docker images on Fly.io. This flexibility, the free tier and a long list of features make it the new favourite hosting platform for developers who need a place to learn and try stuff out.</p>
<p>Go and <a target="_blank" href="https://fly.io/">play around</a> if you didn't get the chance yet. Laterrrrr.</p>
]]></content:encoded></item><item><title><![CDATA[Mustache templates with OpenAPI specs]]></title><description><![CDATA[Best features of the OpenAPI code generation]]></description><link>https://beppecatanese.hashnode.dev/mustache-templates-with-openapi-specs</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/mustache-templates-with-openapi-specs</guid><category><![CDATA[APIs]]></category><category><![CDATA[OpenApi]]></category><category><![CDATA[mustache]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[REST API]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Sun, 12 Jun 2022 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/3DkouQeZjp4/upload/73e66d8a5183081f6becf9bbc51490cf.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article explores the Mustache templates, in the context of the OpenAPI specification, and <strong>the underrated features that can help developers</strong> in optimizing the code generation.</p>
<p>At <a target="_blank" href="https://www.adyen.com/">Adyen</a>, we adopted OpenAPI specs some time ago and we have created our own Mustache templates to streamline the generation of the <a target="_blank" href="https://github.com/Adyen">Adyen SDKs</a> (in various languages) every time there is a new release of the payment APIs.</p>
<p><a target="_blank" href="https://mustache.github.io/">Mustache</a> is a logic-less template framework used to generate output that must conform to a structure and format we want to control. The applications are several: generating code, HTML, configuration files, etc…</p>
<p>They are logic-less (meaning the actual templating engine must take care of the conversion logic), simple (having just the features you need — no-frills) and open-source.</p>
<h3 id="heading-in-a-nutshell">In a nutshell</h3>
<p>Given a template</p>
<pre><code class="lang-bash">Hello {{name}} {{lastname}}
</code></pre>
<p>and a data structure</p>
<pre><code class="lang-bash">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Beppe"</span>,
  <span class="hljs-string">"lastname"</span>: <span class="hljs-string">"Catanese"</span>
}
</code></pre>
<p>the template engine will know how to produce</p>
<pre><code class="lang-bash">Hello Beppe Catanese
</code></pre>
<h3 id="heading-openapi-language-templates">OpenAPI language templates</h3>
<p>The <a target="_blank" href="https://github.com/OpenAPITools/openapi-generator">OpenAPI Generator</a> project allows the generation of (client, server and models) code starting from a valid OpenAPI specification, either <code>json</code> or <code>yaml</code>. This is an extremely valuable feature for API-driven products where code and API specs change often and need to be kept aligned (at ideally small effort).</p>
<p>In this workflow Mustache templates play a key role: for each language and framework OpenAPI provides a default implementation (based on predefined Mustache templates) which works really well in most cases and can be tuned further (extending the templates) when needed.</p>
<h3 id="heading-becoming-a-mustache-master">Becoming a Mustache Master</h3>
<p>Let’s dive into the more advanced features that make Mustache templates powerful.</p>
<h4 id="heading-parameters-list">Parameters list</h4>
<p>Use <code>^last</code> to add the comma between parameters unless it is the last one</p>
<pre><code class="lang-bash">{{<span class="hljs-comment">#allParams}}paramName *{{{dataType}}}{{^-last}}, {{/-last}}{{/allParams}}</span>
</code></pre>
<pre><code class="lang-bash">-&gt; user *string, address *string, nationality *string
</code></pre>
<h4 id="heading-naming-parameters-with-a-sequence">Naming parameters with a sequence</h4>
<p>Use <code>-index</code> to access the index while traversing an array or list</p>
<pre><code class="lang-bash">{{<span class="hljs-comment">#allParams}}req{{-index}} *{{{dataType}}}{{^-last}}, {{/-last}}{{/allParams}}</span>
</code></pre>
<pre><code class="lang-bash">-&gt; req1 *string, req2 *string, req3 *string
</code></pre>
<h4 id="heading-distinguish-between-parameters">Distinguish between parameters</h4>
<p>While <code>allParams</code> gives access to the whole list of parameters, it is useful to make a distinction when generating method signatures or documentation</p>
<pre><code class="lang-bash">{{<span class="hljs-comment">#pathParams}}...{{/pathParams}}</span>
{{<span class="hljs-comment">#bodyParams}}...{{/bodyParams}}</span>
{{<span class="hljs-comment">#queryParams}}...{{/queryParams}}</span>
</code></pre>
<h4 id="heading-comments">Comments</h4>
<p>Comments are useful in templates too, but rarely seen</p>
<pre><code class="lang-bash">/**
Info about the method 
{{! comments to be ignore when parsing the template}} 
**/
</code></pre>
<h4 id="heading-custom-delimiter">Custom delimiter</h4>
<p>The default delimiters <code>{{</code> and <code>}}</code> can be overridden (some scripting languages use brace brackets). This is convenient when you need to include curly braces in your output.</p>
<pre><code class="lang-bash">{{! change delimiters to &lt;% and %&gt;}}
{{=&lt;% %&gt;=}}
{{! put it back }}
&lt;%={{ }}=%&gt;
</code></pre>
<h4 id="heading-first-and-last-element">First and last element</h4>
<p>While traversing arrays it is useful to access easily the first and the last element, for example, the <a target="_blank" href="https://go.dev/tour/basics/2">Go imports</a> group all modules in a list starting and finishing with parenthesis</p>
<pre><code class="lang-bash">{{<span class="hljs-comment">#-first}}</span>
import (
{{/-first}}
    <span class="hljs-string">"{{import}}"</span>
{{<span class="hljs-comment">#-last}}</span>
)
{{/-last}}
</code></pre>
<pre><code class="lang-bash">-&gt; import (
     <span class="hljs-string">"fmt"</span>
     <span class="hljs-string">"math"</span>
   )
</code></pre>
<h4 id="heading-lambda-functions">Lambda functions</h4>
<p>There is a small set of functions available during the OpenAPI code generation: those are convenient when you need to lowercase a package name or camelCase a method.</p>
<pre><code class="lang-bash">lowercase(Beppe) -&gt; beppe
uppercase(Beppe) -&gt; BEPPE
titlecase(Beppe likes mustache) -&gt; Beppe Likes Mustache
camelcase(Beppe-Catanese) -&gt; BeppeCatanese
indented -&gt; add indentation
</code></pre>
<h3 id="heading-create-custom-generator">Create custom generator</h3>
<p>When specific customisation is necessary OpenAPI code generation allows to extend the specific-language generator to add (or redefine) the generation logic. The approach by extension is pretty straightforward:</p>
<p>1: extend the client code generator (for example implementing the renaming of the <code>operationId</code> attribute)</p>
<p>2: generate the code using the new generator</p>
<p>Generate the client code using the new CodeGen implementation</p>
<pre><code class="lang-bash">java -jar openapi-generator-cli.jar generate \
-i /openapi.yaml -t templates/go -g go \
-p packageName=Checkout -o src/checkout \
-g org.mycompany.codegen.MyGoClientCodegen
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Check out our <a target="_blank" href="https://github.com/Adyen/adyen-go-api-library">Go Library</a> to see the customisation of the Mustache templates and how the code generation is performed starting from the <a target="_blank" href="https://github.com/Adyen/adyen-openapi">Adyen OpenAPI specs</a>. Get ready for more articles and insights about our work with OpenAPI (i.e. generating server stubs, testing, mocking and validation).</p>
<p>Lateeeeeer!</p>
]]></content:encoded></item><item><title><![CDATA[E2E testing with Playwright and Docker]]></title><description><![CDATA[Automated testing of the Adyen Sample integrations]]></description><link>https://beppecatanese.hashnode.dev/e2e-testing-with-playwright-and-docker</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/e2e-testing-with-playwright-and-docker</guid><category><![CDATA[playwright]]></category><category><![CDATA[E2ETesting]]></category><category><![CDATA[Docker]]></category><category><![CDATA[github-actions]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Sun, 27 Mar 2022 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/k24rOBJ2D_0/upload/c065f19b403d179efa7a618a12f15baa.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://playwright.dev/">Playwright</a> is a modern framework that simplifies the creation and maintenance of web application end-to-end (E2E) testing. The landscape of e2e testing solutions, to be honest, is already rich with tools and frameworks, however, Playwright joins the party with some distinctive features (cross-platform, cross-browser, cross-language) and a powerful maintainer (Microsoft).</p>
<p>This blog post presents <strong>secrets and practises of using Playwright with Docker</strong> with a specific focus on:</p>
<ol>
<li><p>use the official Playwright Docker image (with some extra tips)</p>
</li>
<li><p>build and run a custom Playwright Docker image</p>
</li>
<li><p>how to integrate the Playwright Docker image in the CI/CD pipeline</p>
</li>
</ol>
<blockquote>
<p>The article shares some of the lesson learnt by implementing E2E testing of the Adyen Sample integrations with Playwright, Docker and GithubActions</p>
</blockquote>
<h3 id="heading-playwright-test-case">Playwright test case</h3>
<p>First, let’s look at a simple test to understand how it is written and executed.</p>
<pre><code class="lang-bash">const { <span class="hljs-built_in">test</span>, expect } = require(<span class="hljs-string">'@playwright/test'</span>);
</code></pre>
<pre><code class="lang-bash"><span class="hljs-built_in">test</span>(<span class="hljs-string">'Card'</span>, async ({ page, baseURL }) =&gt; {
</code></pre>
<pre><code class="lang-bash">   // check page title
   await page.goto(<span class="hljs-string">'/'</span>);     
   await expect(page).toHaveTitle(/Checkout Demo/);  
   // click on button  
   await page.locator(<span class="hljs-string">'text="Card"'</span>).click();
</code></pre>
<p>The test can be written in various <a target="_blank" href="https://playwright.dev/docs/languages">languages</a> and run from the command line with <code>npx playwright test</code> .</p>
<h3 id="heading-using-the-playwright-docker-image">Using the Playwright Docker image</h3>
<p>Playwright makes available an image on <a target="_blank" href="https://hub.docker.com/_/microsoft-playwright">Docker Hub</a> that includes Node, all necessary dependencies, and the browsers. It is extremely convenient to run the tests in a preconfigured environment without the need for extra setup.</p>
<p>Run the Playwright image at the root of your project. The assumption is that the test code is found in the<code>tests</code> directory (otherwise change the scripts accordingly):</p>
<pre><code class="lang-bash"><span class="hljs-comment"># run in the root of your Playwright project</span>
docker run -v <span class="hljs-variable">$PWD</span>:/tests -w /tests --rm -it mcr.microsoft.com/playwright:v1.16.2-focal /bin/bash
</code></pre>
<blockquote>
<p>Note the image tag <code>focal</code> for Ubuntu 20.04 (Focal Fossa): although there are other options (ie Ubuntu 18.04 Bionic Beaver) this works fine on Mac and Github Actions.</p>
</blockquote>
<p>The above command starts an interactive <code>bash</code> session in the container hosting the Playwright environment: execute the commands to add the dependencies of the application, download the browsers and kick off the test execution.</p>
<ul>
<li><p><code>npm install</code>: install all dependencies of your application in the local <code>node_modules</code> folder.</p>
</li>
<li><p><code>npx playwright install</code>: install the supported browsers.</p>
</li>
<li><p><code>npx playwright test</code>: run all the tests.</p>
</li>
</ul>
<pre><code class="lang-bash"><span class="hljs-comment"># you are now inside the container (bash)</span>
root@f4cfe077964d:/e2e<span class="hljs-comment"># npm install</span>
</code></pre>
<pre><code class="lang-bash">root@f4cfe077964d:/e2e<span class="hljs-comment"># npx playwright install</span>
Downloading Playwright build of chromium v939194 - 138.4 Mb [====================] 100% 0.0s
Playwright build of chromium v939194 downloaded to /ms-playwright/chromium-939194
Downloading Playwright build of firefox v1304 - 73.6 Mb [====================] 100% 0.0s
Playwright build of firefox v1304 downloaded to /ms-playwright/firefox-1304
Downloading Playwright build of webkit v1578 - 58.7 Mb [====================] 100% 0.0s
Playwright build of webkit v1578 downloaded to /ms-playwright/webkit-1578
</code></pre>
<pre><code class="lang-bash">root@a818ca0fe10a:/e2e<span class="hljs-comment"># npx playwright test</span>
</code></pre>
<h4 id="heading-some-tips">Some tips</h4>
<p>Let’s look at some useful customisations.</p>
<p><strong>Configure the target URL</strong></p>
<p>The URL of the application to be tested is defined in the <code>playwright.config.js</code> . It is never a good idea to hardcode it but instead aims at keeping the flexibility to test against different environments (i.e. localhost or a staging server), for example reading an environment variable:</p>
<pre><code class="lang-bash">use: {
  baseURL: process.env.URL || <span class="hljs-string">'http://localhost:8080'</span>,
</code></pre>
<p>It is now straightforward to define the URL value at runtime:</p>
<pre><code class="lang-bash">root@a818ca0fe10a:/e2e<span class="hljs-comment"># URL=http://myapp.com npx playwright test</span>
</code></pre>
<p><strong>Install selected extensions</strong></p>
<p>There is no need to install all extensions if the tests must run only on selected browsers:</p>
<pre><code class="lang-bash">root@a818ca0fe10a:/e2e<span class="hljs-comment"># npx playwright install chromium</span>
</code></pre>
<p><strong>Run selected tests</strong></p>
<p>Specify a single test (or a subset) :</p>
<pre><code class="lang-bash"><span class="hljs-comment"># test named dropin or starting with dropin</span>
root@a818ca0fe10a:/e2e<span class="hljs-comment"># npx playwright test dropin</span>
</code></pre>
<p><strong>Test against localhost</strong></p>
<p>Most likely the application under development (in your IDE) is running on localhost, however, this makes it tricky when you want to run the Playwright Docker container to test it.</p>
<pre><code class="lang-bash">root@a818ca0fe10a:/e2e<span class="hljs-comment"># curl -I http://localhost:8080</span>
curl: (7) Failed to connect to localhost port 8080: Connection refused
</code></pre>
<p>Whaaatta!? <code>localhost</code> is not reachable, the reason being the <a target="_blank" href="https://www.cloudsavvyit.com/14114/how-to-connect-to-localhost-within-a-docker-container/">Docker Networking</a>: the <code>localhost</code> from inside the container doesn’t resolve to the host (unless you run on Linux with the <code>--network=host</code> parameter).</p>
<p>The first workaround is to use the built-in <code>host.docker.internal</code> address which is always available.</p>
<pre><code class="lang-bash">root@a818ca0fe10a:/e2e<span class="hljs-comment"># curl -I http://host.docker.internal:8080</span>
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 5345
Server: Werkzeug/2.0.2 Python/3.8.2
Date: Tue, 22 Mar 2022 16:24:46 GMT
</code></pre>
<p>Another (slightly more laborious) workaround is to map the IP address of the host (your machine) with a newly defined hostname (for example let’s call it <code>docker</code> ).</p>
<pre><code class="lang-bash"><span class="hljs-comment"># get IP</span>
ipconfig getifaddr en0
xxx.xxx.xxx.xxx
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># docker run adding host `docker`</span>
docker run -v <span class="hljs-variable">$PWD</span>:/tests --add-host=docker:xxx.xxx.xxx.xxx -w /tests --rm -it mcr.microsoft.com/playwright:v1.16.2-focal /bin/bash
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># host `docker` resolves to host</span>
root@a818ca0fe10a:/e2e<span class="hljs-comment"># curl -I http://docker:8080</span>
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 5345
Server: Werkzeug/2.0.2 Python/3.8.2
Date: Tue, 22 Mar 2022 16:24:46 GMT
</code></pre>
<blockquote>
<p><strong>Important note in case of developing an Adyen integration</strong>: any chosen URL must be specified in the Allowed-Origin list to ensure the client-side requests are authorised</p>
</blockquote>
<h3 id="heading-create-your-own-custom-playwright-docker-image">Create your own custom Playwright Docker image</h3>
<p>Another option is to create a custom Playwright Docker image to “bake” configuration, dependencies and tests altogether.</p>
<pre><code class="lang-bash">FROM mcr.microsoft.com/playwright:v1.16.2-focal

<span class="hljs-comment"># copy project (including tests)</span>
COPY . /e2e

WORKDIR /e2e

<span class="hljs-comment"># Install dependencies</span>
RUN npm install
<span class="hljs-comment"># Install browsers</span>
RUN npx playwright install

<span class="hljs-comment"># Run playwright test</span>
CMD [ <span class="hljs-string">"npx"</span>, <span class="hljs-string">"playwright"</span>, <span class="hljs-string">"test"</span>, <span class="hljs-string">"--reporter=list"</span> ]
</code></pre>
<p>The testing suite can be executed by running the Docker image and passing any env variables (i.e. URL of the application).</p>
<pre><code class="lang-bash">docker build -t custom-playwright .
docker run -it --rm -e URL=http://myapp.com --name customplaywright custom-playwright
</code></pre>
<pre><code class="lang-bash">Running 5 tests using 2 workers
</code></pre>
<pre><code class="lang-bash">✓  [chromium] › card.spec.js:5:1 › Card (3s)
  ✓  [chromium] › card2.spec.js:5:1 › Card2 (3s)
  ✓  [chromium] › dropin.spec.js:5:1 › Dropin SEPA (2s)
  ✓  [chromium] › ideal.spec.js:4:1 › iDEAL (2s)
  ✓  [chromium] › webhook.spec.js:5:1 › Webhook Notification (198ms)
</code></pre>
<h3 id="heading-playwright-e2e-in-the-cicd">Playwright E2E in the CI/CD</h3>
<p>Building a custom Docker image makes little sense if you only run the tests locally however, if you want to include the E2E testing in the CI/CD pipeline then it gets exciting. Meet <a target="_blank" href="https://github.com/adyen-examples">Adyen Sample integrations</a>!</p>
<h4 id="heading-payment-checkout-example">Payment Checkout example</h4>
<p>A Sample integration is a working example of a payment checkout with the Adyen platform. It is a simple and effective open-source application that shows how the payment methods appear and execute.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*8stMsrbFswtuElvuocjuyg.png" alt /></p>
<p>Payment checkout — screenshot by the author</p>
<p>Given the variety of languages and frameworks supported by the Adyen platform, we maintain more than 12 samples that are similar in terms of UI and features, but with a different backend. The containerization of the Playwright tests is therefore really valuable to us since it allows us to define a <strong>single testing suite to validate multiple applications</strong> (on every git push and/or pull request).</p>
<p>We have effectively created on-the-fly an environment that runs both the tester application and the application being tested. At the end of the automated testing, the environment no longer exists.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*Khc-cTknef0OtLpcegJeJQ.png" alt /></p>
<p>Workflow of the CI/CD pipeline — Image by author</p>
<p>Let’s look at the GithubActions <a target="_blank" href="https://github.com/adyen-examples/adyen-python-online-payments/blob/main/.github/workflows/e2e.yml">workflow file</a> of one of these applications:</p>
<ul>
<li><p>first check the source code, build the Docker image and run it on <code>8080</code></p>
</li>
<li><p>pull and run the Testing Suite Docker image targeting the application listening on port <code>8080</code></p>
</li>
</ul>
<pre><code class="lang-bash">name: E2E (Playwright)

on:
  push:
  pull_request:
    branches: [ main ]

<span class="hljs-built_in">jobs</span>:
  checkout:
    runs-on: ubuntu-latest
    steps:
      <span class="hljs-comment"># checkout application code</span>
      - name: Checkout project
        uses: actions/checkout@v2
      <span class="hljs-comment"># build application Docker image</span>
      - name: Build image (application)
        run: docker build -t test-image:latest .
      <span class="hljs-comment"># run application Docker image</span>
      - name: Start container (application)
        run: docker run --rm -d --name test-image -p 8080:8080 -e ADYEN_API_KEY=<span class="hljs-string">"<span class="hljs-variable">${{ secrets.ADYEN_API_KEY }</span>}"</span> -test-image:latest
      - name: Run Testing Suite container
        <span class="hljs-comment"># run testing suite Docker image</span>
        run: docker run --rm --name adyen-testing-suite --network host ghcr.io/adyen-examples/adyen-testing-suite:latest
</code></pre>
<h3 id="heading-conclusions">Conclusions</h3>
<p>I hope the article helps to shed some light on Playwright with Docker, which is not extensively (yet) used or documented. The valuable takeaway here is, by using Docker, it is possible to design custom E2E workflows portable between development environments and CI/CD engines.</p>
<p>Follow <a target="_blank" href="https://twitter.com/beppecatanese">me</a> and <a target="_blank" href="https://twitter.com/AdyenDevs">Adyen Developers</a> for more. Happy testing!</p>
<hr />
<h2 id="heading-references">References</h2>
<p>Adyen integration samples on <a target="_blank" href="https://github.com/adyen-examples">Github</a></p>
<p>Adyen Testing Suite on <a target="_blank" href="https://github.com/adyen-examples/adyen-testing-suite">Github</a></p>
<p>Playwright on Docker <a target="_blank" href="https://playwright.dev/docs/docker">page</a></p>
]]></content:encoded></item><item><title><![CDATA[Multiple Docker images on Heroku]]></title><description><![CDATA[Comparing heroku.yml and the Heroku Deploy Maven plugin]]></description><link>https://beppecatanese.hashnode.dev/multiple-docker-images-on-heroku</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/multiple-docker-images-on-heroku</guid><category><![CDATA[Docker]]></category><category><![CDATA[Docker compose]]></category><category><![CDATA[Heroku]]></category><category><![CDATA[maven]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Wed, 09 Mar 2022 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cYUMaCqMYvI/upload/e10d6ee401150d5222ce72981aa58f69.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, I am presenting the options to <strong>deploy multiple Docker images</strong> on Heroku. Following the microservices philosophy developers like splitting responsibilities into standalone services which are more easily developed, containerized and deployed.</p>
<p>Although Heroku support for Docker is <a target="_blank" href="https://devcenter.heroku.com/articles/container-registry-and-runtime">awesome</a> the platform is not living up to its standards when dealing with multiple containers (á la Docker Compose to be clear).</p>
<p>The post blog will discuss and compare two options:</p>
<ul>
<li><p>using <strong>heroku.yml</strong></p>
</li>
<li><p>using the <strong>Heroku Docker Maven</strong> plugin</p>
</li>
</ul>
<h3 id="heading-using-herokuyml">Using heroku.yml</h3>
<p>Given the popularity (and convenience) of <a target="_blank" href="https://docs.docker.com/compose/">Docker Compose</a> Heroku was introduced <code>heroku.yml</code> back in 2018 with the goal of simulating the same workflow. Did it work? Let’s have a look.</p>
<h4 id="heading-herokuyml">heroku.yml</h4>
<p>The goal of<code>heroku.yml</code> is to encapsulate the Docker configuration of your Heroku application, the different images involved and the stages of the build.</p>
<pre><code class="lang-bash">setup:
  addons:
    - plan: heroku-postgresql
      as: DATABASE
  config:
    MY_VAR: my value
    MY_VAR_2: another value
build:
  docker:
    web: web/Dockerfile
    worker: worker1/Dockerfile
    worker: worker2/Dockerfile
<span class="hljs-comment"># release:</span>
  <span class="hljs-comment"># copy resources</span>
  <span class="hljs-comment"># skip in this example</span>
<span class="hljs-comment"># run:</span>
  <span class="hljs-comment"># startup script</span>
  <span class="hljs-comment"># skip in this example</span>
</code></pre>
<p>There are 4 phases managed by <code>heroku.yml</code>:</p>
<ul>
<li><p><code>setup</code> to provision add-ons (i.e. database, cache) and set the config vars (environment variables)</p>
</li>
<li><p><code>build</code> to create the Docker images (in the example above one web and 2 workers) by specifying the process type and path of each Dockerfile</p>
</li>
<li><p><code>release</code> to run tasks required during the application release (for example copy assets or upgrade database structure)</p>
</li>
<li><p><code>run</code> to define commands to execute at application startup (note: this can be skipped and instead rely on the Dockerfile<code>CMD</code> instruction)</p>
</li>
</ul>
<p>Once the <code>heroku.yml</code> is ready the process is straightforward: create the application, set the container stack (Heroku must know you want to use Docker) and push the file.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># create the Heroku app</span>
$ heroku create myapp
$ heroku stack:<span class="hljs-built_in">set</span> container
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># commit (in the repository's root)</span>
$ git add heroku.yml
$ git commit -m <span class="hljs-string">"Added heroku.yml"</span>
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># push to heroku </span>
git push heroku main
</code></pre>
<h4 id="heading-pros-and-cons">Pros and Cons</h4>
<p>Using <code>heroku.yml</code> is overall pretty convenient: the whole application (from pre-requisites to deployment scripts) is defined in a single file and you can build multiple Docker images at once. Good stuff.</p>
<p>However, there are some <strong>limitations</strong>:</p>
<ul>
<li><p>it is not possible to create multiple images and deploy them on <strong>different</strong> applications</p>
</li>
<li><p>it requires <code>git</code> to trigger the deployment pipeline (by pushing the changes to the Heroku git repository)</p>
</li>
<li><p>only a single <code>web</code> Dyno is possible</p>
</li>
<li><p>it addresses the build and deployment needs, but it cannot un-deploy nor check the application(s) information.</p>
</li>
</ul>
<p>Given the above, I have created a Maven plugin to provide the extra features.</p>
<h3 id="heading-heroku-docker-maven-plugin">Heroku Docker Maven plugin</h3>
<p>The idea behind the <a target="_blank" href="https://github.com/gcatanese/heroku-docker-maven-plugin">Heroku Docker Maven plugin</a> is to manage multiple Dockerized services directly from the IDE (or command line) using Maven.</p>
<p>It delivers its best (IMHO) in a Maven multi-module project where each module has its own Dockerfile (maybe not suitable for production but I reckon convenient for development and testing purposes).</p>
<h4 id="heading-goals">Goals</h4>
<p>The plugin supports currently 4 goals:</p>
<ul>
<li><p><code>deploy</code>: build, push and release the Docker image(s) to Heroku</p>
</li>
<li><p><code>info</code>: print some information about the Heroku application(s) defined in the Maven POM file(s)</p>
</li>
<li><p><code>start</code>: start (scale up) the Heroku application(s)</p>
</li>
<li><p><code>stop</code>: stop (scale down) the Heroku application(s)</p>
</li>
</ul>
<h4 id="heading-prerequisites">Prerequisites</h4>
<p>The <a target="_blank" href="https://devcenter.heroku.com/articles/heroku-cli">Heroku CLI</a> must be available in the environment/hosting running the Maven plugin and, obviously, an account to log into the Docker registry.</p>
<h4 id="heading-configuration">Configuration</h4>
<p>Configure the plugin in the <strong>parent POM</strong></p>
<pre><code class="lang-bash">&lt;build&gt;
  &lt;plugins&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;com.tweesky.cloudtools&lt;/groupId&gt;
      &lt;artifactId&gt;heroku-docker-maven-plugin&lt;/artifactId&gt;
      &lt;version&gt;0.0.1&lt;/version&gt;
    &lt;/plugin&gt;
  &lt;/plugins&gt;
&lt;/build&gt;
</code></pre>
<p>Configure each service (sub-module) accordingly</p>
<pre><code class="lang-bash">&lt;build&gt;
  &lt;plugins&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;com.tweesky.cloudtools&lt;/groupId&gt;
      &lt;artifactId&gt;heroku-docker-maven-plugin&lt;/artifactId&gt;
      &lt;configuration&gt;
        &lt;appName&gt;serviceOne&lt;/appName&gt;
        &lt;processType&gt;web&lt;/processType&gt;
        &lt;configVars&gt;
          &lt;VAR_ONE&gt;SomeValue&lt;/VAR_ONE&gt;
          &lt;VAR_TWO&gt;SomeOtherValue&lt;/VAR_TWO&gt;
        &lt;/configVars&gt;
      &lt;/configuration&gt;
    &lt;/plugin&gt;
  &lt;/plugins&gt;
&lt;/build&gt;
</code></pre>
<p>Note above how you can define the application name (<code>appName</code> ), the type of process (<code>processType</code> )and any config vars (<code>configVars</code> ) you might want to provision.</p>
<p>Check out the <a target="_blank" href="https://github.com/gcatanese/MavenMultiModule">MavenMultiModule</a> example on GitHub.</p>
<h4 id="heading-execute">Execute</h4>
<p>Invoke the plugin with the desired goal, for example <code>deploy</code> to build and push all services</p>
<pre><code class="lang-bash">mvn heroku-docker:deploy
</code></pre>
<p>Check the status of the applications</p>
<pre><code class="lang-bash">mvn heroku-docker:info
</code></pre>
<p>It is time to get a coffee ☕ Stop all services to save on your Heroku free quota ;-)</p>
<pre><code class="lang-bash">mvn heroku-docker:stop
</code></pre>
<h4 id="heading-cicd">CI/CD</h4>
<p>The plugin can also be used with a CI/CD tool, for example, to rebuild and deploy the Docker images after a code push.</p>
<p>On <strong>Github Actions</strong> this turns out to be pretty simple using Maven (passing the Heroku API Key for authentication purposes).</p>
<pre><code class="lang-bash">- name: Heroku Container Registry login
  env:
     HEROKU_API_KEY: <span class="hljs-variable">${{ secrets.HEROKU_API_KEY }</span>}
  run: heroku container:login
- name: Build with Maven      
  env:
     HEROKU_API_KEY: <span class="hljs-variable">${{ secrets.HEROKU_API_KEY }</span>}  
  run: 
    mvn -B heroku-docker:deploy
</code></pre>
<p>See the full <a target="_blank" href="https://github.com/gcatanese/MavenMultiModule/blob/main/.github/workflows/maven.yml">workflow</a> file with all steps.</p>
<h4 id="heading-pros-and-cons-1">Pros and Cons</h4>
<p>While the plugin addresses the <code>heroku.yml</code> limitations (deploy multiple web services, manage multiple applications, no need to configure and use Heroku git) it does require creating (manually) the Heroku application (including the provision of any addon) beforehand.</p>
<h4 id="heading-contributing">Contributing</h4>
<p>The initial version of the Heroku Docker Maven plugin suits my needs (hopefully yours too) however, I am happy to hear feedback to evolve and improve it further.</p>
<p>One very interesting feature to be considered could be the support of<code>docker-compose.yml</code> allowing developers to re-use existing docker-compose files without copying the configuration elsewhere. Interested in contributing? Head to the GitHub repository and/or get in touch!</p>
<hr />
<h3 id="heading-resources">Resources</h3>
<p>GitHub <a target="_blank" href="https://github.com/gcatanese/heroku-docker-maven-plugin">repository</a> with an example using the Heroku Docker Maven plugin</p>
<p>Github <a target="_blank" href="https://github.com/gcatanese/HerokuYmlSample">repository</a> showing how to configure and use <code>heroku.yml</code></p>
]]></content:encoded></item><item><title><![CDATA[Files on Heroku]]></title><description><![CDATA[Heroku file system is ephemeral: applications can write on the file system but any change is discarded when the Dyno (the application host) restarts…]]></description><link>https://beppecatanese.hashnode.dev/files-on-heroku</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/files-on-heroku</guid><category><![CDATA[Heroku]]></category><category><![CDATA[Python]]></category><category><![CDATA[S3]]></category><category><![CDATA[dropbox]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Fri, 09 Apr 2021 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/xmcpNFyaP4c/upload/f581d21708f8d473ec22f102e0266c5c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-options-to-overcome-the-heroku-ephemeral-filesystem-for-free">Options to overcome the Heroku ephemeral filesystem. For free.</h3>
<h3 id="heading-the-challenge">The Challenge</h3>
<p>Heroku file system is <a target="_blank" href="https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem">ephemeral</a>: applications can write on the file system but <strong>any change is discarded</strong> when the Dyno (the application host) restarts, making this option only suitable for temporary data.</p>
<p>It is also important to remember that Heroku implements <a target="_blank" href="https://devcenter.heroku.com/articles/dynos#restarting">cycling</a>: every Dyno reboots (at least) every 24 hours and all local filesystem modifications are deleted.</p>
<h4 id="heading-a-solution">A solution</h4>
<p>Applications that must persist data <strong>should instead rely on an external database or a remote file server</strong>. In this post, we explore several <strong>FREE</strong> available storage options to read and write files programmatically (with Python, although it is of course possible with other programming languages and libraries):</p>
<ul>
<li><p>GitHub</p>
</li>
<li><p>S3</p>
</li>
<li><p>Dropbox</p>
</li>
<li><p>DriveHQ (FTP)</p>
</li>
<li><p>GitLab</p>
</li>
<li><p>GMail</p>
</li>
</ul>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*4SCPR6o1dH12cmY4-p8yfA.jpeg" alt /></p>
<p>Photo by <a target="_blank" href="https://unsplash.com/@brina_blum?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brina Blum</a> on <a target="_blank" href="https://unsplash.com/s/photos/usb?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
<hr />
<h3 id="heading-store-files-on-github">Store files on GitHub</h3>
<p>A valid option is to use Github: it is free, and reliable and developers are already familiar with it.</p>
<blockquote>
<p>Suitable for low traffic, for example saving at regular intervals a single file which contains data updated by the users (like a CSV/JSON file)</p>
</blockquote>
<p>The idea is to store files in any of your Github private or public repositories using the <a target="_blank" href="https://github.com/PyGithub/PyGithub">PyGithub</a> Python module.</p>
<h4 id="heading-github-access-token">GitHub Access Token</h4>
<p>Generate the Github Access Token necessary to authenticate the API calls: go to <code>Account -&gt; Settings -&gt; Developer Settings -&gt; Personal Access Token</code></p>
<p>Grant the token the necessary privileges (read/write into repositories) and NEVER show or share your tokens.</p>
<p>See GitHub documentation if unsure: <a target="_blank" href="https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token">Creating a personal access token</a></p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*ZxcRl7xr08f7lCd-n3mMVA.png" alt="Create Personal Access Token screenshot (Image by author)" /></p>
<p>Create Personal Access Token (Image by author)</p>
<h4 id="heading-write-a-file">Write a file</h4>
<pre><code class="lang-bash">github = Github(<span class="hljs-string">'personal_access_token'</span>)
repository = github.get_user().get_repo(<span class="hljs-string">'my_repo'</span>)
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># path in the repository</span>
filename = <span class="hljs-string">'files/file.json'</span>
</code></pre>
<pre><code class="lang-bash">content = <span class="hljs-string">'{\"name\":\"beppe\",\"city\":\"amsterdam\"}'</span>
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># create with commit message</span>
f = repository.create_file(filename, <span class="hljs-string">"create_file via PyGithub"</span>, content)
</code></pre>
<h4 id="heading-read-a-file">Read a file</h4>
<pre><code class="lang-bash">github = Github(<span class="hljs-string">'personal_access_token)
repository = github.get_user().get_repo('</span>my_repo<span class="hljs-string">')</span>
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># path in the repository</span>
filename = <span class="hljs-string">'files/file.json'</span>
</code></pre>
<pre><code class="lang-bash">file = repository.get_contents(filename)
<span class="hljs-built_in">print</span>(file.decoded_content.decode())
</code></pre>
<h3 id="heading-amazon-s3">Amazon S3</h3>
<p>Amazon S3 (Simple Storage Service) is the remote storage offered by Amazon. It is not entirely free but extremely cheap.<br />A great advantage of this option is that there are several other S3-compatible storage services, which makes it easier to move to a different provider if needed.</p>
<blockquote>
<p>Suitable if you need a production-ready file system (managing folders, support large files, scale up volume and size)</p>
</blockquote>
<p>The Python <a target="_blank" href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">boto3</a> library is a simple and highly popular module for accessing and managing S3 resources.</p>
<h4 id="heading-aws-credentials">AWS Credentials</h4>
<p>Obtain the AWS credentials from the <a target="_blank" href="https://console.aws.amazon.com/iam/home#/home">IAM Console</a></p>
<h4 id="heading-get-a-file">Get a file</h4>
<pre><code class="lang-bash">session = boto3.session.Session()
</code></pre>
<pre><code class="lang-bash">s3 = session.client(
    service_name=<span class="hljs-string">'s3'</span>,
    aws_access_key_id=<span class="hljs-string">'xyz'</span>,
    aws_secret_access_key=<span class="hljs-string">'abc'</span>
)
</code></pre>
<pre><code class="lang-bash">s3.download_file(Bucket=<span class="hljs-string">'bucket_name'</span>, Key=<span class="hljs-string">'dir/a.txt'</span>, Filename=/tmp/a.txt)
</code></pre>
<h4 id="heading-put-a-file">Put a file</h4>
<pre><code class="lang-bash">session = boto3.session.Session()
</code></pre>
<pre><code class="lang-bash">s3 = session.client(
    service_name=<span class="hljs-string">'s3'</span>,
    aws_access_key_id=<span class="hljs-string">'xyz'</span>,
    aws_secret_access_key=<span class="hljs-string">'abc'</span>
)
</code></pre>
<pre><code class="lang-bash">s3.upload_file(Bucket=<span class="hljs-string">'bucket_name'</span>, Key=<span class="hljs-string">'dir/a.txt'</span>, Filename=/tmp/a.txt)
</code></pre>
<h4 id="heading-delete-a-file">Delete a file</h4>
<pre><code class="lang-bash">session = boto3.session.Session()
</code></pre>
<pre><code class="lang-bash">s3 = session.client(
    service_name=<span class="hljs-string">'s3'</span>,
    aws_access_key_id=<span class="hljs-string">'xyz'</span>,
    aws_secret_access_key=<span class="hljs-string">'abc'</span>
)

s3.delete_object(Bucket=<span class="hljs-string">'bucket_name'</span>, Key=<span class="hljs-string">'dir/a.txt'</span>);
</code></pre>
<h3 id="heading-dropbox">Dropbox</h3>
<p><a target="_blank" href="https://www.dropbox.com/">Dropbox</a> is a file hosting service that offers various plans at different prices. The <strong>Dropbox Basic</strong> account is free and allows storing up to 2GB of files.</p>
<blockquote>
<p>Suitable when the files need to be accessed or modified outside the application (i.e. via the Dropbox web application or Google Docs).</p>
</blockquote>
<p>The intuitive Web User Interface can be used to create, edit and download files; there is a nice integration with Google Docs and Office Online and a powerful <a target="_blank" href="https://www.dropbox.com/developers/documentation/python">Python Dropbox SDK</a>.</p>
<h4 id="heading-dropbox-setup">Dropbox Setup</h4>
<p>Sign up for a Dropbox account (it is also possible to register via your Google account) then head to the Dropbox <a target="_blank" href="https://www.dropbox.com/developers/apps">App Console</a>. Create a new application, define the permissions (ie files.content.write, files.content.read) and generate the <code>Access Token</code>.</p>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*YTRCR0WYE4bmrM6zsg31Pw.png" alt="Dropbox App Console (image by author)" /></p>
<p>Dropbox App Console (image by author)</p>
<h4 id="heading-create-a-file">Create a file</h4>
<pre><code class="lang-bash">dbx = dropbox.Dropbox(<span class="hljs-string">'access_token'</span>)
</code></pre>
<pre><code class="lang-bash">filename = <span class="hljs-string">'/local_files/file.json'</span>
dbx.files_upload(f.read(), filename, mute=True)
</code></pre>
<h4 id="heading-get-a-file-1">Get a file</h4>
<pre><code class="lang-bash">dbx = dropbox.Dropbox(<span class="hljs-string">'access_token'</span>)
</code></pre>
<pre><code class="lang-bash">filename = <span class="hljs-string">'/dropbox_root/file.json'</span>
f, r = dbx.files_download(filename)
</code></pre>
<pre><code class="lang-bash"><span class="hljs-built_in">print</span>(r.content)
</code></pre>
<h3 id="heading-drivehq">DriveHQ</h3>
<p><a target="_blank" href="https://www.drivehq.com/">DriveHQ</a> is a file server provider supporting FTP and WebDAV protocols. It offers a “Free 5 GB Basic” Service.</p>
<blockquote>
<p>Suitable when developers are familiar with the FTP protocols and tools.</p>
</blockquote>
<p>Sign up for a DriveHQ Basic Account. Import the Python <code>ftplib</code> module (for storing and fetching files via FTP) and perform the login with the same credentials using the Python API.</p>
<h4 id="heading-upload-a-new-file">Upload a new file</h4>
<pre><code class="lang-bash">def upload_file():
</code></pre>
<pre><code class="lang-bash">  ftp_host = <span class="hljs-string">"ftp.drivehq.com"</span>
  ftp_username = <span class="hljs-string">"my_username"</span>
  ftp_password = <span class="hljs-string">"my_password"</span>
</code></pre>
<pre><code class="lang-bash">  filename = <span class="hljs-string">"/files/file.csv"</span>
  localfile = <span class="hljs-string">"tmp/file.csv"</span>
</code></pre>
<pre><code class="lang-bash">  <span class="hljs-comment"># open session</span>
  session = ftplib.FTP(ftp_host, ftp_username, ftp_password)
</code></pre>
<pre><code class="lang-bash">  file = open(localfile, <span class="hljs-string">'rb'</span>)  <span class="hljs-comment"># file to send</span>
  session.storbinary(<span class="hljs-string">'STOR '</span>+filename, file)  <span class="hljs-comment"># send the file</span>

  file.close()  <span class="hljs-comment"># close file and FTP session</span>
  session.quit()
</code></pre>
<h4 id="heading-download-an-existing-file">Download an existing file</h4>
<pre><code class="lang-bash">def download_file():
</code></pre>
<pre><code class="lang-bash">  ftp_host = <span class="hljs-string">"ftp.drivehq.com"</span>
  ftp_username = <span class="hljs-string">"my_username"</span>
  ftp_password = <span class="hljs-string">"my_password"</span>
</code></pre>
<pre><code class="lang-bash">  filename = <span class="hljs-string">"/files/file.csv"</span>
  localfile = <span class="hljs-string">"tmp/file.csv"</span>
</code></pre>
<pre><code class="lang-bash">  <span class="hljs-comment"># open session</span>
  session = ftplib.FTP(ftp_host, ftp_username, ftp_password)
</code></pre>
<pre><code class="lang-bash">  f = open(localfile, <span class="hljs-string">'wb'</span>)  <span class="hljs-comment"># save into local file</span>
  session.retrbinary(<span class="hljs-string">'RETR '</span> + filename, f.write, 1024)

  file.close()  <span class="hljs-comment"># close file and FTP session</span>
  session.quit()
</code></pre>
<pre><code class="lang-bash">  <span class="hljs-comment"># Open local file</span>
  f = open(localfile, <span class="hljs-string">'rb'</span>)
  content = f.read()
</code></pre>
<h3 id="heading-gitlab">GitLab</h3>
<p>GitLab can also be used as a simple file repository.</p>
<blockquote>
<p>Suitable for low traffic, for example saving regularly a file which contains data updated by the users (like a CSV/JSON file)</p>
</blockquote>
<p>Store files on any of your Gitlab private or public repositories using <a target="_blank" href="https://python-gitlab.readthedocs.io/en/stable/index.html">Python-Gitlab</a></p>
<h4 id="heading-gitlab-personal-access-token">Gitlab Personal Access Token</h4>
<p>Generate a GitHub Personal Access Token: go to <code>Account -&gt; Settings -&gt; Access Tokens -&gt; Add Personal Access Token</code></p>
<p>Grant the token the necessary privileges (read/write into repositories) and NEVER show or share your tokens.</p>
<h4 id="heading-read-a-file-1">Read a file</h4>
<pre><code class="lang-bash">gl = gitlab.Gitlab(<span class="hljs-string">'https://gitlab.com'</span>, private_token=<span class="hljs-string">'token'</span>)
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># get repository by ID</span>
project = gl.projects.get(123)
</code></pre>
<pre><code class="lang-bash">f = project.files.get(file_path=<span class="hljs-string">'files/config.json'</span>, ref=<span class="hljs-string">'master'</span>)
</code></pre>
<h4 id="heading-write-a-file-1">Write a file</h4>
<pre><code class="lang-bash">gl = gitlab.Gitlab(<span class="hljs-string">'https://gitlab.com'</span>, private_token=<span class="hljs-string">'token'</span>)
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># get repository by ID</span>
project = gl.projects.get(123)
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># define name and content</span>
filename = <span class="hljs-string">'files/config.json'</span>
content = <span class="hljs-string">"{name: \"Beppe\", city: \"Amsterdam\"}"</span>
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># payload</span>
data = {
    <span class="hljs-string">'branch'</span>: <span class="hljs-string">'master'</span>,
    <span class="hljs-string">'commit_message'</span>: <span class="hljs-string">'Push file'</span>,
    <span class="hljs-string">'actions'</span>: [
        {
            <span class="hljs-string">'action'</span>: <span class="hljs-string">'create'</span>,
            <span class="hljs-string">'file_path'</span>: filename,
            <span class="hljs-string">'content'</span>: content,
        }
    ]
}

commit = project.commits.create(data)
</code></pre>
<h3 id="heading-gmail">Gmail</h3>
<p>Send a file by email using your Gmail account and the <a target="_blank" href="https://github.com/kootenpv/yagmail">yagmail</a> Python library.</p>
<blockquote>
<p>A very basic approach but it might be useful to make an application file available (i.e. send debug data to the administrators)</p>
</blockquote>
<h4 id="heading-security">Security</h4>
<p>You will need to use your Gmail credentials as well as enabling <code>Allow less secure apps</code> in the Gmail settings, see <a target="_blank" href="https://www.google.com/settings/security/lesssecureapps">here</a>.</p>
<pre><code class="lang-bash">yag = yagmail.SMTP(<span class="hljs-string">'username'</span>, <span class="hljs-string">'password'</span>)
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># define recipient and file to attach</span>
recipient = <span class="hljs-string">"beppe@example.com"</span>
attachment= <span class="hljs-string">'tmp/attach.txt'</span>
</code></pre>
<pre><code class="lang-bash">contents = [<span class="hljs-string">'Body of email'</span>, attachment]
</code></pre>
<pre><code class="lang-bash">yag.send(recipient, <span class="hljs-string">'File from Python app'</span>, contents)
</code></pre>
<h3 id="heading-conclusions">Conclusions</h3>
<p>Undoubtedly storing data in a database allows more flexibility, better maintenance and faster data retrieval, however, the additional complexity is not always necessary. <strong>Dealing with simple files is a lot easier</strong> and sometimes just enough to meet the developer’s needs.</p>
<p>All code snippets shown in the article can be found in the GitHub repository <a target="_blank" href="https://github.com/gcatanese/HerokuFiles">HerokuFiles</a>. You can catch me on <a target="_blank" href="https://twitter.com/beppecatanese">Twitter</a> for questions and suggestions.</p>
<p>Happy coding ✌️</p>
]]></content:encoded></item><item><title><![CDATA[From Apple Silicon to Heroku Docker Registry Without Swearing]]></title><description><![CDATA[Build Intel64-compatible Docker images from Mac M1]]></description><link>https://beppecatanese.hashnode.dev/heroku-docker-registry</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/heroku-docker-registry</guid><category><![CDATA[Docker]]></category><category><![CDATA[Heroku]]></category><category><![CDATA[macOS]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Fri, 02 Apr 2021 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731661493930/2c1fae02-e450-40f9-bf27-83bac6c73a35.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Docker Desktop (natively) and Heroku CLI (with Rosetta) work nicely on the Apple M1 processor, however, a locally built Docker image will not successfully deploy onto the <strong>Heroku Docker Registry</strong>.</p>
<p>In a previous article <a target="_blank" href="https://beppecatanese.hashnode.dev/deploy-to-heroku-from-a-macbook-m1-heroku-cli-or-githubactions">Deploy to Heroku From a MacBook M1: Heroku CLI or GitHubActions</a>, I described how it is possible (and very convenient) to build a Docker image and deploy it to Heroku using GitHub Actions. Here I am going to look at how to, in a Mac development environment, <strong>build and release</strong> an image that is compatible with the Heroku Docker Registry runtime.</p>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*b2myM3P4snFpD84oT9fUaQ.png" alt /></p>
<p>Image by author</p>
<hr />
<h3 id="heading-what-is-happening">What is happening?</h3>
<p>Building and deploying Docker containers on <a target="_blank" href="https://devcenter.heroku.com/articles/container-registry-and-runtime">Heroku Docker Registry</a> is pretty simple. First, satisfy the prerequisites :</p>
<ul>
<li><p>Login into Heroku (<code>heroku login</code>) and Heroku Docker Registry (<code>heroku:container login</code>)</p>
</li>
<li><p>Place the <code>Dockerfile</code> in the root folder</p>
</li>
</ul>
<p>Build and release the application with a few simple steps:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># create Heroku app</span>
% heroku create myapp
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># set ConfigVar (if env variables are necessary)</span>
% heroku config:<span class="hljs-built_in">set</span> PARAM=<span class="hljs-string">"value"</span>
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># build and push Docker image</span>
% heroku container:push web -a myapp
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># release</span>
% heroku container:release web -a myapp
</code></pre>
<p>That should all be enough: the “push” and “release” phases of the build complete successfully, however when accessing the application (<code>myapp.herokuapp.com</code>) the <strong>“Error: Exec format error”</strong> appears.</p>
<p>Whaaat daa..</p>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*uGcnAcqLUIe3eHYZIq5Uiw.png" alt="Screenshot of Heroku logs showing ‘Error” Exec format error" /></p>
<p>Screenshot by author</p>
<p>Let’s look into the image created by the Heroku command above</p>
<pre><code class="lang-bash">% docker inspect registry.heroku.com/myapp/web
</code></pre>
<pre><code class="lang-bash">[
    {
        <span class="hljs-string">"Id"</span>: <span class="hljs-string">"sha256:38005888ba52553018768ee5f4997d4d599fbeafed88c166f2c0a71fc6b49abc"</span>,
        <span class="hljs-string">"RepoTags"</span>: [
            <span class="hljs-string">"registry.heroku.com/myapp/web:latest"</span>
        ],
...
   },
   <span class="hljs-string">"Architecture"</span>: <span class="hljs-string">"arm64"</span>,
   <span class="hljs-string">"Os"</span>: <span class="hljs-string">"linux"</span>,
</code></pre>
<p>Docker is by design multi-platform and can run on different architectures, however, <strong>the images must match the platform</strong> they will be run on. Which is not our case.</p>
<h3 id="heading-option-a-buildx">Option A: buildx</h3>
<p><a target="_blank" href="https://github.com/docker/buildx">Buildx</a> is a Docker plugin that allows, amongst other features, to build multi-platform images.</p>
<p>We are developing on the Mac ARM architecture but we want to create a x86-compatible image. The solution is <strong>NOT to use the</strong> <code>heroku:container push</code> command but rather to build the image locally with Docker <code>buildx</code>.</p>
<pre><code class="lang-bash">docker buildx build --platform linux/amd64 -t myapp .
<span class="hljs-comment"># tag image to match Heroku naming conventions</span>
docker tag myapp registry.heroku.com/myapp/web
<span class="hljs-comment"># push</span>
docker push registry.heroku.com/myapp/web
</code></pre>
<p>Once pushed the image can be released</p>
<pre><code class="lang-bash">heroku container:release web -a myapp
</code></pre>
<h3 id="heading-option-b-set-dockerdefaultplatform">Option B: set <code>DOCKER_DEFAULT_PLATFORM</code></h3>
<p>The <code>DOCKER_DEFAULT_PLATFORM</code> environment variable permits to set the default platform for the commands that take the <code>--platform</code> flag.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> DOCKER_DEFAULT_PLATFORM=linux/amd64
</code></pre>
<p>You can now go ahead and use the standard Heroku CLI commands (since Docker underneath will run with the platform indicated by the setting above).</p>
<pre><code class="lang-bash"><span class="hljs-comment"># build and push Docker image</span>
% heroku container:push web -a myapp
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># release</span>
% heroku container:release web -a myapp
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>The two solutions presented are both valid: my personal choice is to “delegate” the build to a CI/CD tool (like GitHub Actions), or to settle for the first option (<code>buildx</code>) which keeps the flexibility of switching easily between platforms (it may not the case when using an environment variable).</p>
<p>Check out the <a target="_blank" href="https://github.com/gcatanese/TelegramBotDemo">GitHub repository</a> showing various options to deploy on Heroku.</p>
<p>Happy coding ✌️</p>
]]></content:encoded></item><item><title><![CDATA[Deploy to Heroku From a MacBook M1: Heroku CLI or GitHubActions]]></title><description><![CDATA[Setting up a new laptop is always fun, but this time with my new flashy MacBook Pro and the Apple-designed M1 chip is a different experience. The device is…]]></description><link>https://beppecatanese.hashnode.dev/deploy-to-heroku-from-a-macbook-m1-heroku-cli-or-githubactions</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/deploy-to-heroku-from-a-macbook-m1-heroku-cli-or-githubactions</guid><category><![CDATA[Heroku]]></category><category><![CDATA[github-actions]]></category><category><![CDATA[Apple M1]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Fri, 19 Mar 2021 11:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Setting up a new laptop is always fun, but this time with my new flashy MacBook Pro and the <strong>Apple-designed M1 chip</strong> is a different experience. The device is simply amazing and very performing, however, it has created headaches, especially for developers who need to run a variety of tools that are not yet compatible with ARM architecture.</p>
<p>This post is about how to deploy (*) on Heroku your projects developed on the Apple Silicon M1:</p>
<ul>
<li><p>using Heroku Command Line Interface (with Rosetta)</p>
</li>
<li><p>creating a GitHubActions pipeline</p>
</li>
</ul>
<p>(*) note that deploying with git (<code>git push heroku master</code>) works fine (Git Version Control has full native Apple Silicon support), but installing Heroku CLI is still necessary to create new applications, scale up and down, define Config Vars, etc..</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*A7aZOfv40TCy1G8WRDFYlw.jpeg" alt /></p>
<p>Image by <a target="_blank" href="https://pixabay.com/users/lukgehr-16347051/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5856077">Lukas Gehrer</a> from <a target="_blank" href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5856077">Pixabay</a></p>
<hr />
<h3 id="heading-heroku-cli-with-rosetta">Heroku CLI with Rosetta</h3>
<p>The Heroku CLI is <strong>not yet natively running</strong> on the Apple M1 chip, therefore the only option at the moment is to install and run it with <a target="_blank" href="https://developer.apple.com/documentation/apple-silicon/about-the-rosetta-translation-environment">Rosetta</a> (<strong>Rosetta</strong> is the translation process that allows applications designed for Intel processors to run apps on Apple silicon).</p>
<p><strong>New Terminal Application</strong></p>
<p>Locate the Terminal application in ‘Finder-&gt;Applications-&gt;Utilities’ and (with right-click) duplicate the application (i.e. Terminal with Rosetta).</p>
<p>Open (with right-click) ‘Get Info’ and enable Rosetta.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*YAcUbR3CE5NXug3AxISJfA.png" alt /></p>
<p>Open using Rosetta</p>
<p><strong>You have now 2 Terminal apps</strong> which make it extremely convenient to switch between ARM and Intel modes. Over time applications will migrate to the new architecture and eventually the Rosetta mode will no longer be needed.</p>
<p><strong>Install Rosetta</strong></p>
<p>During the very first usage of the “Terminal with Rosetta” you will be prompted to install Rosetta: this is obviously the easiest way.</p>
<p>Rosetta can also be installed manually running</p>
<pre><code class="lang-bash">/usr/sbin/softwareupdate --install-rosetta
</code></pre>
<p><strong>Install (again) brew</strong></p>
<p>If you have installed Homebrew earlier (before enabling Rosetta) you have already downloaded M1-compatible packages on your Mac. Try:</p>
<pre><code class="lang-bash">% <span class="hljs-built_in">which</span> brew
/opt/homebrew/bin/brew
</code></pre>
<p>to confirm it is the case and verify the default location (Homebrew for Apple Silicon is expected to be installed in <code>/opt/homebrew</code> ).</p>
<p><strong>Make sure</strong> you open the “Terminal with Rosetta” and then install Homebrew again</p>
<pre><code class="lang-bash">/bin/bash -c <span class="hljs-string">"<span class="hljs-subst">$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)</span>"</span>
</code></pre>
<pre><code class="lang-bash">==&gt; Checking <span class="hljs-keyword">for</span> `sudo` access (<span class="hljs-built_in">which</span> may request your password).Password:
==&gt; This script will install:
/usr/<span class="hljs-built_in">local</span>/bin/brew
/usr/<span class="hljs-built_in">local</span>/share/doc/homebrew
/usr/<span class="hljs-built_in">local</span>/share/man/man1/brew.1
/usr/<span class="hljs-built_in">local</span>/share/zsh/site-functions/_brew
/usr/<span class="hljs-built_in">local</span>/etc/bash_completion.d/brew
/usr/<span class="hljs-built_in">local</span>/Homebrew
....
</code></pre>
<p>The expected location of x64 Homebrew is instead<code>/usr/local/bin</code>.</p>
<p><strong>There are now 2 Homebrews and this is perfectly fine</strong>: do not forget whichever <code>brew</code> is first found in PATH will run when you call <code>brew</code>. A smart idea is to create an alias for Rosetta Homebrew to simplify usage and avoid confusion</p>
<pre><code class="lang-plaintext">alias rbrew='/usr/local/bin/brew'
</code></pre>
<pre><code class="lang-plaintext"># Rosetta brew
% which rbrew
rbrew: aliased to /usr/local/bin/brew
</code></pre>
<pre><code class="lang-plaintext"># Native brew
% which brew
/opt/homebrew/bin/brew
</code></pre>
<p><strong>Install Heroku</strong></p>
<p>Heroku CLI can now be installed using Terminal with Rosetta</p>
<pre><code class="lang-plaintext">rbrew tap heroku/brew &amp;&amp; rbrew install heroku
</code></pre>
<p>The Heroku Command Line should now be operational, verify and login</p>
<pre><code class="lang-plaintext">% heroku --version
% heroku login
% heroku apps
</code></pre>
<h3 id="heading-docker-deployment-with-github-actions">Docker Deployment with GitHub Actions</h3>
<p>While the Heroku command line can be used to build and push Docker images into the <strong>Heroku Docker Registry</strong> it is a good idea to use a CI tool for doing this.</p>
<p><a target="_blank" href="https://github.com/features/actions">GitHub Actions</a> is the GitHub CI/CD which allows GitHub users to compile, test, package, deploy, and a lot more… it is free, extendible (more actions and integrations popping up every day) and extensively documented with guides and examples.</p>
<p><strong>Create a new Workflow</strong></p>
<p>In your Git repository head straight to Actions and create a new “Workflow”</p>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*3puRQTa_o79BVgScOWiMFA.png" alt /></p>
<p>GitHub Actions workflows</p>
<p>The creation is simple and supported with a long list of templates, but ultimately it is possible to edit the action YAML file (which can be found in the <code>.github/workflows</code> folder).</p>
<p>The sample below is a Java application built with JDK11 and Maven, but the same concept applies to other programming languages and build tools.</p>
<pre><code class="lang-plaintext">name: Build &amp; Push to Heroku Docker Registry
</code></pre>
<pre><code class="lang-plaintext">on:
  push:
    branches: [ main ]
</code></pre>
<pre><code class="lang-plaintext">jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    # checkout source
    - name: Git Checkout
      uses: actions/checkout@v1
    # config JDK
    - name: Set up JDK 11
      uses: actions/setup-java@v1
      with:
        java-version: 11
    # Build the Jar
    - name: Build with Maven
      run: mvn -B package --file pom.xml
    # Login in Heroku
    - name: Heroku Container Registry login
      env: 
        HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}
      run: heroku container:login 
    # Build and push Docker image
    - name: Build and push
      env:
        HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}
      run: heroku container:push -a ${{ secrets.HEROKU_APP_NAME }} web 
    # Release 
    - name: Release
      env:
        HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}
      run: heroku container:release -a ${{ secrets.HEROKU_APP_NAME }} web
</code></pre>
<p>The pipeline is triggered by every git push on the main branch (this can <a target="_blank" href="https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#on">customised</a> and even done manually)</p>
<pre><code class="lang-plaintext">on:
  push:
    branches: [ main ]
</code></pre>
<p>The steps of the pipelines are:</p>
<ul>
<li><p>preparing: checkout of the source code and configuration of the JDK</p>
</li>
<li><p>build: compile, build, test and package with Maven</p>
</li>
<li><p>deploy: authenticate Heroku token, build and push the Docker image</p>
</li>
</ul>
<p><strong>Secrets</strong></p>
<p>The pipeline requires secrets (<code>HEROKU_API_KEY</code> (*) and <code>HEROKU_APP_NAME</code>) and those can be safely configured in the GitHub repository (go to <code>Settings-&gt;Secrets-&gt;New repository secret</code>) and never exposed in the source code.</p>
<p>(*) Grab the<code>HEROKU_API_KEY</code> from Heroku Dashboard in the Account “API Key” section</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*fE7TtpV06rK4ZFWlqTo7xA.png" alt /></p>
<p>Workflow Summary</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Working on the Apple M1 is a supreme experience, even if some tools still require the Rosetta layer. As time goes by more and more applications will migrate to the ARM architecture and eventually the entire development ecosystem will run natively. Until then some patching and tricks will allow us to survive!</p>
<p>Check out the GitHub repository <a target="_blank" href="https://github.com/gcatanese/SpringBootService">SpringBootService</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Bring your Telegram Chatbot to the next level]]></title><description><![CDATA[Telegram is a popular platform for developing chatbots: excellent documentation, a vibrant community, various libraries and tons of examples. If you are…]]></description><link>https://beppecatanese.hashnode.dev/bring-your-telegram-chatbot-to-the-next-level</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/bring-your-telegram-chatbot-to-the-next-level</guid><category><![CDATA[chatbot]]></category><category><![CDATA[telegram]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Fri, 19 Mar 2021 11:00:00 GMT</pubDate><content:encoded><![CDATA[<hr />
<h3 id="heading-bring-your-telegram-chatbot-to-the-next-level">Bring your Telegram Chatbot to the next level</h3>
<h4 id="heading-discover-advanced-features-that-can-make-a-difference">Discover advanced features that can make a difference</h4>
<p>Telegram is a popular platform for developing chatbots: excellent documentation, a vibrant community, various libraries and tons of examples.</p>
<p>If you are <strong>getting started</strong> there are plenty of tutorials around, especially on <a target="_blank" href="https://medium.com/search?q=telegram%20bot">Medium</a>. <a target="_blank" href="https://stackoverflow.com/questions/tagged/telegram-bot">Stackoverflow</a> is also a great resource for answering questions and understanding issues (your author is often spotted there to try to help fellow developers out 🤓).</p>
<p>This article instead focuses on <strong>more advanced aspects</strong> related to the implementation of a Telegram bot using <a target="_blank" href="https://python-telegram-bot.readthedocs.io/en/stable/">Python Telegram Bot</a>:</p>
<ul>
<li><p>Pull vs Webhook</p>
</li>
<li><p>Grab the chat ID</p>
</li>
<li><p>Display “Typing…” and suggest answers</p>
</li>
<li><p>Deep linking</p>
</li>
<li><p>Send media and files</p>
</li>
</ul>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*TJMlSskm4YqOhY2WDz5UkA.jpeg" alt="User chatting on Telegram" /></p>
<p>Photo by <a target="_blank" href="https://unsplash.com/@christianw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christian Wiediger</a> on <a target="_blank" href="/s/photos/telegram?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
<hr />
<h3 id="heading-polling-mode-to-work-locally">Polling mode to work locally</h3>
<p>Telegram Bot can work with a <strong>Pull</strong> or with a <strong>Push</strong> mechanism (see further Webhooks). The pull mechanism is where the bot (your code) is checking regularly for new available messages on the server.</p>
<p>Everyone agrees this is not an ideal approach (unnecessary waste of resources, messages are discarded after 24 hours), but it is convenient when developing locally. (no tunneling software like <code>ngrok</code> is required).</p>
<pre><code class="lang-bash">def main():
    updater = Updater(<span class="hljs-string">'myTelegramToken'</span>)

    dp = updater.dispatcher
</code></pre>
<pre><code class="lang-bash">    <span class="hljs-comment"># define command handler</span>
    dp.add_handler(CommandHandler(<span class="hljs-string">"help"</span>, help_command_handler))
    <span class="hljs-comment"># define message handler</span>
    dp.add_handler(MessageHandler(Filters.text, main_handler))
</code></pre>
<pre><code class="lang-bash">    updater.start_polling()
</code></pre>
<h3 id="heading-webhooks-on-production">Webhooks on production</h3>
<p>Once the bot is ready for deployment it is time to enable the Webhook: doing so Telegram will push the updates to the registered Webhook endpoint and your service gets busy only when there are new incoming messages.</p>
<pre><code class="lang-bash">updater.start_webhook(listen=<span class="hljs-string">"0.0.0.0"</span>,
                      port=3978,
                      url_path=<span class="hljs-string">'myTelegramToken'</span>)
updater.bot.setWebhook(<span class="hljs-string">'https://example.com/svc/myTelegramToken'</span>)
</code></pre>
<p><strong>Note</strong>: webhook works nicely with a serverless architecture or with ‘on-demand’ nodes. I have deployed Telegram webhooks on <strong>Heroku Free Tier</strong> which goes to sleep after 30 minutes of inactivity, but if a new message is pushed the Heroky Dyno starts up and the message is consumed within a few seconds.</p>
<p><strong>Note 2</strong>: depending on where the bot is deployed the port number needs to be configured. On Heroku, for example, the port is typically defined by the PORT environment variable and should never be hardcoded.</p>
<p><strong>How to register a webhook</strong></p>
<p>You can do this by calling a the <code>setWebhook</code> URL: use your private token and pass the URL (must be HTTPS) of the webhook.</p>
<pre><code class="lang-bash">https://api.telegram.org/bot{myTelegramToken}/setWebhook?url=https://example.com/svc
</code></pre>
<p><strong>Switch between Pull and Push mode</strong></p>
<p>I find it extremely convenient to switch programmatically between polling and webhook using an environment variable: the default is <code>polling</code> to work locally but, when deploying on the live system, it can be overridden (to <code>webhook</code>).</p>
<pre><code class="lang-bash"><span class="hljs-comment"># read MODE env variable, fall back to 'polling' when undefined</span>
mode = os.environ.get(<span class="hljs-string">"MODE"</span>, <span class="hljs-string">"polling"</span>)
</code></pre>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> DefaultConfig.MODE == <span class="hljs-string">'webhook'</span>:
  <span class="hljs-comment"># enable webhook</span>
  updater.start_webhook(listen=<span class="hljs-string">"0.0.0.0"</span>,
                      port=3978,
                      url_path=<span class="hljs-string">'myTelegramToken'</span>)
  updater.bot.setWebhook(<span class="hljs-string">'https://example.com/svc/myTelegramToken'</span>)
</code></pre>
<pre><code class="lang-bash"><span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># enable polling</span>
    updater.start_polling()
</code></pre>
<h3 id="heading-obtain-the-chat-id">Obtain the Chat ID</h3>
<p>Replying to an incoming message is pretty simple.</p>
<pre><code class="lang-bash">update.message.reply_text(<span class="hljs-string">"Hi there!"</span>)
</code></pre>
<p>however, sometimes we want to be able to initiate the message without the user asking anything (for example a notification after a few days to re-engage our users).</p>
<p>Retrieve (and save) the <code>chat_id</code> which is found in the JSON payload of the message sent by the user (yes, you need at least one message)</p>
<pre><code class="lang-bash">{<span class="hljs-string">'update_id'</span>: 527095032, 
 <span class="hljs-string">'message'</span>: {
     <span class="hljs-string">'message_id'</span>: 412, 
     <span class="hljs-string">'date'</span>: 1615991013, 
     <span class="hljs-string">'chat'</span>: {
        <span class="hljs-string">'id'</span>: 931365322, 
        <span class="hljs-string">'type'</span>: <span class="hljs-string">'private'</span>, 
        <span class="hljs-string">'username'</span>: <span class="hljs-string">'gcatanese'</span>, 
        ....
</code></pre>
<p>When parsing the payload Python do not forget that different messages have slightly different JSON.</p>
<pre><code class="lang-bash">def get_chat_id(update, context):
    chat_id = -1

    <span class="hljs-keyword">if</span> update.message is not None:
        <span class="hljs-comment"># text message</span>
        chat_id = update.message.chat.id
    <span class="hljs-keyword">elif</span> update.callback_query is not None:
        <span class="hljs-comment"># callback message</span>
        chat_id = update.callback_query.message.chat.id
    <span class="hljs-keyword">elif</span> update.poll is not None:
        <span class="hljs-comment"># answer in Poll</span>
        chat_id = context.bot_data[update.poll.id]

    <span class="hljs-built_in">return</span> chat_id
</code></pre>
<h3 id="heading-suggested-actions">Suggested Actions</h3>
<p>Guide the conversation providing the user with predefined options to choose from. This can be achieved using the <code>InlineKeyboardMarkup</code> , a keyboard that appears along the message (like a question).</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*csaW5wmFbYxZQ_nHof16VA.png" alt="Multiple Option buttons displayed in a Telegram chat" /></p>
<p>Image by author</p>
<p>Here is the Python snippet to create the options:</p>
<pre><code class="lang-bash">options = []
options.append(InlineKeyboardButton(text=<span class="hljs-string">'Text'</span>, callback_data=<span class="hljs-string">'1'</span>))
options.append(InlineKeyboardButton(text=<span class="hljs-string">'File'</span>, callback_data=<span class="hljs-string">'2'</span>))
options.append(InlineKeyboardButton(text=<span class="hljs-string">'GoogleDoc'</span>, callback_data=<span class="hljs-string">'3'</span>))
options.append(InlineKeyboardButton(text=<span class="hljs-string">'Gallery'</span>, callback_data=<span class="hljs-string">'4'</span>))
</code></pre>
<pre><code class="lang-bash">reply_markup = InlineKeyboardMarkup([options])
</code></pre>
<pre><code class="lang-bash">context.bot.send_message(chat_id=get_chat_id(update, context), text=<span class="hljs-string">'What would you like to receive?'</span>, reply_markup=reply_markup)
</code></pre>
<p>It is important to understand that the response will be processed by a <code>CallbackQueryHandler</code> and the incoming JSON payload is different from the plain text message.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># input from text message</span>
text = update.message.text
<span class="hljs-comment"># selection from callback</span>
choice = update.callback_query.data
</code></pre>
<p><strong>Note</strong>: Once a selection is made the Options disappear from the chat.</p>
<p><strong>Note2</strong>: define <code>callback_data</code> using a constant value which will be used to decide what to do. Unlike the <code>text</code> on the button, this value should not change as it is not visible to the user.</p>
<pre><code class="lang-bash">choice = update.callback_query.data
</code></pre>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> choice == <span class="hljs-string">'1'</span>:
  <span class="hljs-comment"># Choice 1: Text</span>
  update.callback_query.message.edit_text(<span class="hljs-string">'You have chosen Text'</span>)
</code></pre>
<h3 id="heading-show-typing">Show “Typing…”</h3>
<p>Display the Typing indicator is a common feature in chatbots: users are informed a message is about to arrive, even if there is a little delay.</p>
<pre><code class="lang-bash">context.bot.send_chat_action(chat_id=get_chat_id(update, context), action=telegram.ChatAction.TYPING, timeout=1)
time.sleep(1)
</code></pre>
<p><strong>Note</strong>: while displaying the Typing indicator I normally introduce a short delay to create the feeling of a real conversation.</p>
<h3 id="heading-deep-linking-with-an-additional-parameter">Deep linking with an additional parameter</h3>
<p><a target="_blank" href="https://core.telegram.org/bots#deep-linking">Deep linking</a> is a mechanism that allows one to open a conversation with a given bot. This is useful to share the link to the bot on websites, emails or Social Media.</p>
<p>When defining the deep link it is possible to add parameter:</p>
<pre><code class="lang-bash">https://t.me/username_bot?start=signup
</code></pre>
<p>The link opens the Telegram application prompting <code>start</code> the conversation with the bot. The additional parameter is passed to the <code>CommandHandler</code> processing of the <code>/start</code> command.</p>
<pre><code class="lang-bash">def start_command_handler(update, context):
    param_value = context.args[0]
    update.message.reply_text(<span class="hljs-string">'Value is '</span> + param_value)
</code></pre>
<h3 id="heading-send-a-file">Send a File</h3>
<p>The chatbot can send files (i.e. PDFs, Office) in different ways.</p>
<p>Use <code>send_document</code> with the full URL to the file:</p>
<pre><code class="lang-bash">url=<span class="hljs-string">'https://github.com/gc/TelegramBotDemo/raw/main/test.pdf'</span>
context.bot.send_document(chat_id=get_chat_id(update, context), document=url)
</code></pre>
<p><strong>Note</strong>: this approach requires a URL which points directly to the file.</p>
<p>Another approach is to first download locally the file and then send it with the same method <code>send_document</code> .</p>
<pre><code class="lang-bash"><span class="hljs-comment"># fetch from Google Drive</span>
url = <span class="hljs-string">'https://drive.google.com/file/d/0BZ3dWQ2ZXVOdE1V/view'</span>
r = requests.get(url, allow_redirects=True)
<span class="hljs-comment"># save local copy</span>
open(<span class="hljs-string">'file.ppt'</span>, <span class="hljs-string">'wb'</span>).write(r.content)
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># send file to user</span>
context.bot.send_document(chat_id=get_chat_id(update, context), document=open(<span class="hljs-string">'file.ppt'</span>, <span class="hljs-string">'rb'</span>), filename=<span class="hljs-string">"Presentation.pptx"</span>)
</code></pre>
<p><strong>Note</strong>: this approach is usually necessary when the URL does not point directly to a file, but it is an endpoint streaming out the content on demand.</p>
<h3 id="heading-create-a-media-gallery">Create a Media Gallery</h3>
<p>A cool feature is sending a group of media like photos, videos and audio.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*pPN6nAwstDCOctYVwrbNrg.png" alt="Gallery of images displayed in a Telegram chat" /></p>
<p>Image by author</p>
<pre><code class="lang-bash">list = []
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># define list of files</span>
list.append(InputMediaPhoto(media=<span class="hljs-string">'https://../mintie.jpg'</span>, caption=<span class="hljs-string">'Mint'</span>))
list.append(InputMediaPhoto(media=<span class="hljs-string">'https://../pinkie.png'</span>, caption=<span class="hljs-string">'Pink'</span>))
list.append(InputMediaPhoto(media=<span class="hljs-string">'https://../orangie.png'</span>, caption=<span class="hljs-string">'Orange'</span>))

context.bot.send_media_group(chat_id=get_chat_id(update, context), media=list)
</code></pre>
<p><strong>Note</strong>: the bot can send up to 10 media files at the same time.</p>
<p><strong>Note2</strong>: each message counts within the Telegram Rate limits (30 messages per second) therefore you can send up to 3 messages with 10 media each (in total 30) but, in this case, you cannot add anything else in the same transaction (not even a simple text message).</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>I hope the article helps to understand some more advanced scenarios and discover features that can make your Telegram chatbot a little bit more special. My advice is to always consider first what the users are looking for (why would they chat? ) and then design it in a way that makes their conversation frictionless and enjoyable: striking a good balance determines the success of your chatbot.</p>
<p>Check out the <a target="_blank" href="https://github.com/gcatanese/TelegramBotDemo">GitHub repo</a> where you can grab the code snippets shown above.</p>
<p>Happy chatting!</p>
]]></content:encoded></item><item><title><![CDATA[Twitter Direct Messages like a Pro (with Tweepy)]]></title><description><![CDATA[Direct Messages have been available for a while on Twitter. This is not a surprise as messaging has undoubtedly a huge impact on the way we communicate…]]></description><link>https://beppecatanese.hashnode.dev/twitter-direct-messages-like-a-pro-with-tweepy</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/twitter-direct-messages-like-a-pro-with-tweepy</guid><category><![CDATA[Python]]></category><category><![CDATA[Twitter]]></category><category><![CDATA[Tweepy]]></category><category><![CDATA[messaging]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Wed, 10 Mar 2021 11:00:00 GMT</pubDate><content:encoded><![CDATA[<hr />
<h3 id="heading-twitter-direct-messages-like-a-pro-with-tweepy">Twitter Direct Messages like a Pro (with Tweepy)</h3>
<p>Direct Messages have been available for a while on Twitter. This is not a surprise as messaging has undoubtedly a huge impact on the way we communicate, work and connect every day.</p>
<p>On Social Platforms messaging can play a pivotal role for businesses that want to extend their reach (increase followers), create a unique brand or deliver ‘not-less-than-excellence’ through their customer experience and support.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*squsEkPEiWNbIF4tS0WFNA.jpeg" alt /></p>
<p>Photo by <a target="_blank" href="https://unsplash.com/@olegmagni?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Oleg Magni</a> on <a target="_blank" href="https://unsplash.com/s/photos/twitter-messaging?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
<p>Here <strong>1)</strong> I will discuss a few facts and considerations on how Direct Private Messages can deliver value to a brand or an organisation, <strong>2)</strong> I will dive into some technical examples (for the techies 🤓 out there) on how a Twitter BOT can read and send DMs using Tweepy.</p>
<hr />
<h3 id="heading-value-of-direct-messages">Value of Direct Messages</h3>
<p>DMs can be adopted for pursuing different objectives:</p>
<ul>
<li><p>cherish your follower base: any new follower can be welcomed with a “Thank you for following us!” message</p>
</li>
<li><p>engagement: send a message to followers to inform them about something important (changes in services or policies) or a new opportunity (available offers or useful tips)</p>
</li>
<li><p>personal: reaching privately in a friendly and personal way can create a connection between the brand and the followers</p>
</li>
<li><p>exploit the capabilities: Twitter DMs support up to 10k characters which allows customers to submit their queries without the constraint of a standard Tweet (max 280 chars)</p>
</li>
</ul>
<p>Direct Messages <strong>should not be abused</strong> as they will turn into Spam pushing interest away and casting a dark shadow over the image of the brand. For the same reason, they <strong>should not be ignored</strong> or considered a low priority with late or poor responses.</p>
<p>Finally, when ready and committed, enable the option to receive DMs from everyone: this is important when the goal is allowing customers and users to be able to reach you.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*G0fExaJOWG5HZ8jVEaZGbA.png" alt /></p>
<p>Check “Allow message requests from everyone”</p>
<h3 id="heading-snippets-and-dev-practises-of-a-twitter-bot">Snippets and Dev Practises of a Twitter Bot</h3>
<p><a target="_blank" href="https://www.tweepy.org/">Tweepy</a> is one of the most popular libraries to access Twitter. It provides a wrapper around the Twitter REST API to simplify configuration, authentication and invocation of the endpoints.</p>
<p>Tweepy support for Twitter Direct Messages is great.</p>
<p>In the following sections we will see how to perform the following:</p>
<ul>
<li><p>setup the access to Twitter API</p>
</li>
<li><p>fetch DMs sent to a Twitter account</p>
</li>
<li><p>send a message</p>
</li>
<li><p>delete a message</p>
</li>
</ul>
<h3 id="heading-authentication">Authentication</h3>
<p>The setup and authentication are straightforward. First, apply for a Twitter Developer Account on the <a target="_blank" href="https://developer.twitter.com/en">Twitter Dev</a> site to obtain the necessary access keys.</p>
<pre><code class="lang-plaintext">import tweepy

# Authenticate access
auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET")
auth.set_access_token("ACCESS_TOKEN", "ACCESS_TOKEN_SECRET")

# Create API handler
api = tweepy.API(auth)
</code></pre>
<p>Never hardcode tokens and credentials in the source code, but rather store them in an external file (.env) or (even better) in environment variables.</p>
<h3 id="heading-receive-a-direct-message">Receive a Direct Message</h3>
<p>DMs sent to your account appear in the Messages Inbox. The Tweepy library provides a method to fetch them:</p>
<pre><code class="lang-plaintext">messages = api.list_direct_messages(count=5)
</code></pre>
<pre><code class="lang-plaintext">for message in reversed(messages):
  # who is sending?  
  sender_id = message.message_create["sender_id"]
  # what is she saying?
  text = message.message_create["message_data"]["text"]
</code></pre>
<p>A few remarks about the code above:</p>
<ol>
<li><p>The number of messages fetched by a single API call can be controlled (20 is the default, 50 is the max that can be used)</p>
</li>
<li><p>The list is processed in reverse to read the most recent messages first</p>
</li>
<li><p><strong>All received and sent</strong> messages will be returned (yes, also our replies)</p>
</li>
<li><p>Although the DM appears very quickly in the Twitter Messages Inbox, there is a <strong>delay</strong> before it is available via the API</p>
</li>
</ol>
<p>More at <a target="_blank" href="https://developer.twitter.com/en/docs/twitter-api/v1/direct-messages/sending-and-receiving/api-reference/list-events">Twitter REST API GET Direct Messages</a></p>
<h3 id="heading-send-a-direct-message">Send a Direct Message</h3>
<p>Sending DMs is again a simple operation:</p>
<pre><code class="lang-plaintext">recipient_id = "123"  # ID of the user
api.send_direct_message(recipient_id, "Hoi hoi")
</code></pre>
<p>It can be pretty cool to reply including a <strong>Media</strong>, maybe sending a Thank You gif or a small Intro video.</p>
<pre><code class="lang-plaintext"># upload media
media = api.media_upload(filename='/files/thankyou.png')
</code></pre>
<pre><code class="lang-plaintext"># send with media
recipient_id = "123"  # ID of the user
api.send_direct_message(recipient_id=recipient_id, text='Thank You!', attachment_type='media', attachment_media_id=media.media_id)
</code></pre>
<p>Note the <code>recipient_id</code> is the ID (number) of the Twitter user, not the username (string i.e. @beppecatanese). The numeric User ID can obtained with an API call</p>
<pre><code class="lang-plaintext">user = api.get_user("beppecatanese")
recipient_id = user.id_str
</code></pre>
<p>When replying to a DM we received the <code>recipient_id</code> can be found in the JSON payload of the original message</p>
<pre><code class="lang-plaintext">recipient_id = message.message_create["sender_id"]
</code></pre>
<p>More at <a target="_blank" href="https://developer.twitter.com/en/docs/twitter-api/v1/direct-messages/sending-and-receiving/api-reference/new-event">Twitter REST API POST Direct Message</a></p>
<h3 id="heading-delete-a-direct-message">Delete a Direct Message</h3>
<p>Deleting messaging is also convenient to clean up the Inbox but also to avoid inadvertently replying to the same message.</p>
<p><strong>Note</strong>: I normally delete a message after I reply so I do not need to worry about skipping it next time I download the messages. Obviously this is not strictly necessary but it simplifies the management of the Inbox.</p>
<pre><code class="lang-plaintext"># delete by ID
api.destroy_direct_message(message.id)
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Check out the source code on <a target="_blank" href="https://github.com/gcatanese/1-2-3-Direct-Messages-With-Tweepy">GitHub</a></p>
<p>For Tweepy new starters, I recommend a really good tutorial on <a target="_blank" href="https://realpython.com/twitter-bot-python-tweepy/">Real Python</a></p>
]]></content:encoded></item><item><title><![CDATA[1, 2, 3: SpringBoot, Docker, Nginx, DigitalOcean]]></title><description><![CDATA[This is another step-by-step walkthrough which explains how to dockerize and deploy a SpringBoot microservice behind Nginx. This article aims to help Java…]]></description><link>https://beppecatanese.hashnode.dev/1-2-3-springboot-docker-nginx-digitalocean</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/1-2-3-springboot-docker-nginx-digitalocean</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Docker]]></category><category><![CDATA[DigitalOcean]]></category><category><![CDATA[nginx]]></category><category><![CDATA[Let's Encrypt]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Thu, 14 Jan 2021 11:00:00 GMT</pubDate><content:encoded><![CDATA[<hr />
<h3 id="heading-1-2-3-springboot-docker-nginx-digitalocean">1, 2, 3: SpringBoot, Docker, Nginx, DigitalOcean</h3>
<p>This is another step-by-step walkthrough which explains how to dockerize and deploy a SpringBoot microservice behind Nginx.</p>
<p>This article aims to help Java developers who want to start using popular tools (Docker, Nginx, DockerHub, Certbot) to create a production-ready application. It will also show how to obtain a (<strong>free</strong>!) domain, and set up a (<strong>free</strong>!) SSL certificate and deploy on DigitalOcean. Some DevOps for developers.</p>
<blockquote>
<p>Why 1–2–3? Focus on simple essential aspects, clear code samples and relevant references.</p>
</blockquote>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*QgACnqrDedaIkQ6-_m8G7Q.png" alt /></p>
<p>Image by author</p>
<hr />
<h3 id="heading-digitalocean">DigitalOcean</h3>
<p>DigitalOcean is one of the most popular cloud platforms for deploying and managing applications and websites.</p>
<p>The cheapest plan starts from 5$ per month (there is a Free Trial to start with) which is absolutely worth paying: it gives you access to a <a target="_blank" href="https://www.digitalocean.com/products/droplets/">Droplet</a> (1GB memory, 25GB SSD) with several flavors available and plenty of documentation to read.</p>
<h4 id="heading-architecture">Architecture</h4>
<p>Our architecture will be something like this:</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*zeM41M0g9niHL--SsYH5WA.png" alt /></p>
<p>Image by author</p>
<p>A few interesting remarks: the core components run on Docker while <code>certbot</code> is provided by the Ubuntu VM as well as the storage of the SSL certificates (and any other file and static resource).</p>
<h4 id="heading-steps">Steps</h4>
<p>We will go through the following steps to make it happen:</p>
<ul>
<li><p>create and configure the Droplet</p>
</li>
<li><p>run Nginx on Docker</p>
</li>
<li><p>build and deploy the SpringBoot application</p>
</li>
<li><p>obtain a domain</p>
</li>
<li><p>obtain an SSL certificate (our application will run on HTTPS)</p>
</li>
</ul>
<h3 id="heading-create-a-droplet"><strong>Create a Droplet</strong></h3>
<p>Sign up for DigitalOcean (via your Github account is also possible and very convenient) and go straight into the dashboard to create a basic VM from a “Docker on Ubuntu” image.</p>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*KWz8qA4VIKrYiOXUPFVqfw.jpeg" alt /></p>
<p>Image by author</p>
<p>The setup is pretty much straightforward, but you can also have a look at the <a target="_blank" href="https://www.digitalocean.com/docs/droplets/how-to/create/">How to Create a Droplet</a> to understand all settings and options.</p>
<p>Once created you will see the <strong>IP Address</strong> and can log in into the Droplet.</p>
<h3 id="heading-run-nginx">Run Nginx</h3>
<p><a target="_blank" href="https://nginx.org/en/">Nginx</a> will run on Docker using the latest image: I don’t bother to fix a version as I have never seen regressions. Maybe it is something to consider when serving production requests.</p>
<p>When deploying the Nginx base image we only need to provide our own configuration file.</p>
<pre><code class="lang-plaintext"># nginx.conf
</code></pre>
<pre><code class="lang-plaintext">http {
 server {
   listen              443 ssl;
   server_name         myapp.com;
   charset utf-8;
   access_log off;
</code></pre>
<pre><code class="lang-plaintext">location / {
     proxy_pass http://myapp:8080;
   }
 }
</code></pre>
<pre><code class="lang-plaintext">}
events { worker_connections 1024; }
</code></pre>
<p>The file defines the SSL access and a domain (see further), and the proxy_pass, the mechanism to delegate the incoming requests to a downstream application.</p>
<h3 id="heading-springboot-application">SpringBoot Application</h3>
<p>Create a SpringBoot app using <a target="_blank" href="https://start.spring.io/">initializr</a>: in this demo, we only need a simple endpoint (ie /test) to make sure the service is reachable.</p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping
public class AppController {
</code></pre>
<pre><code class="lang-plaintext">  @GetMapping(value = "/test")
  ResponseEntity&lt;?&gt; test(HttpServletRequest request) throws URISyntaxException {
        log.info("/web/test");
        return ResponseEntity.ok().body("Ok");
    }
</code></pre>
<p>You obviously need a little more than this (the SpringApplication file, unit testing, etc..), check out the source code on <a target="_blank" href="https://github.com/gcatanese/1-2-3-SpringBoot-Docker-Nginx-DigitalOcean">GitHub</a> to get all you need.</p>
<p>Once the application is unit tested and run locally we can proceed with the most important step: dockerize it.</p>
<pre><code class="lang-plaintext"># base image
FROM adoptopenjdk/openjdk11:alpine-jre
</code></pre>
<pre><code class="lang-plaintext"># home folder in the Docker image
RUN mkdir -p /software
</code></pre>
<pre><code class="lang-plaintext"># copy config files (application.properties)
ADD config /software/config
# copy jar file
ADD target/myapp.jar /software/myapp.jar
</code></pre>
<pre><code class="lang-plaintext"># run the app
WORKDIR /software
CMD java -Dserver.port=$PORT $JAVA_OPTS -jar myapp.jar
</code></pre>
<p>The application is ready to be built:</p>
<blockquote>
<p>docker build -t mydomain/myapp:latest .</p>
</blockquote>
<p>Run the application on the local Docker to verify it is working:</p>
<blockquote>
<p>docker run -it — rm — name myapp -p 8080:8080 mydomain/myapp:latest</p>
</blockquote>
<p>Hit it now at http://localhost:8080/test</p>
<h4 id="heading-dockerhub">DockerHub</h4>
<p>Once built the image is available on the local environment, to confirm run:</p>
<blockquote>
<p>docker images</p>
</blockquote>
<pre><code class="lang-plaintext">REPOSITORY       TAG      IMAGE ID       CREATED          SIZE
mydomain/myapp   latest   20de1e1496d5   5 minutes ago    95MB
</code></pre>
<p>Nice, but we need to make the same image available on DigitalOcean. We then need to introduce another tool: <a target="_blank" href="https://hub.docker.com/">DockerHub</a>.</p>
<p>DockerHub is a container registry where we can store (for free) public images. Go ahead, sign and login with the Docker CLI.</p>
<blockquote>
<p>docker login</p>
</blockquote>
<p>Push the image</p>
<blockquote>
<p><em>docker push mydomain/myapp:latest</em></p>
</blockquote>
<p>Congrats! You have developed, tested and pushed your Dockerized application to the DockerHub container registry.</p>
<h4 id="heading-docker-compose">Docker Compose</h4>
<p>The last step in this section is to create a docker-compose file. We are going to run multiple containers so one of the options is to define a docker-compose file to keep all the configurations together.</p>
<p>As your application ecosystem grows (for example adding a logging container i.e. logspout) you can just add it in the compose file.</p>
<pre><code class="lang-plaintext">version: "3"
</code></pre>
<pre><code class="lang-plaintext">services:
  myapp:
    image: mydomain/myapp:v0.0.1-a
    container_name: myapp
    ports:
      - "8080:8080"
    networks:
      - my_network
</code></pre>
<pre><code class="lang-plaintext">nginx:
    image: nginx:latest
    container_name: nginx
    restart: always
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    ports:
      - 80:80
      - 443:443
    networks:
      - my_network
</code></pre>
<pre><code class="lang-plaintext">networks:
  my_network:
</code></pre>
<p>Be aware the above is a working-in-progress version of the final docker-compose: we are going to add the <code>letsencrypt</code> configuration.</p>
<h3 id="heading-free-domain">Free Domain</h3>
<p>The application will need its own domain: head to <a target="_blank" href="https://www.freenom.com/en">Freenom</a> where you can get one for free, typically with a <strong>.tk</strong> or <strong>.ml</strong> domain.</p>
<p>You can then create a domain in your DigitalOcean dashboard and link it with the Droplet (configuring the relevant <a target="_blank" href="https://www.digitalocean.com/community/tutorials/how-to-point-to-digitalocean-nameservers-from-common-domain-registrars">nameservers</a>).</p>
<h3 id="heading-free-ssl-certificate">Free SSL Certificate</h3>
<p><strong>Let’s Encrypt</strong> is a non-profit certificate authority which provides free 90-day SSL certificates, which can be always renewed within (and after) the validity window.</p>
<p>We will another tool: <a target="_blank" href="https://certbot.eff.org/">certbot</a>.</p>
<p><strong>Certbot</strong> allows to create and renew SSL certificates from Let’s Encrypt</p>
<pre><code class="lang-plaintext"># install certbot
$ sudo apt install certbot
</code></pre>
<pre><code class="lang-plaintext"># create (or renew) cert
$ certbot certonly --force-renewal -d myapp.com
</code></pre>
<p>There are 2 options to proceed</p>
<pre><code class="lang-plaintext">How would you like to authenticate with the ACME CA?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: Spin up a temporary webserver (standalone)
2: Place files in webroot directory (webroot)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
</code></pre>
<p><strong>Choose #1</strong> to let Certbot handle the challenge using its own built-in web server: it is a lot easier and it does not need any extra plugins (ie Apache for Nginx). The certificate can be found at <em>‘/etc/letsencrypt/live/myapp.com’</em></p>
<p>It is very important however that <strong>no process is already running on port 80</strong>. This is not the case at this stage but it will be during a future renewal: make sure to stop (docker-compose down) the Nginx container before renewing the certificate.</p>
<pre><code class="lang-plaintext"># renew letsencrypt ssl certificate
</code></pre>
<pre><code class="lang-plaintext">$ docker-compose down
$ certbot certonly --force-renewal -d myapp.com
$ docker-compose up -d
</code></pre>
<h3 id="heading-start-it-up">Start it up</h3>
<p>All components are in place and there is a domain with its own SSL certificate. A final change is required in <code>nginx.conf</code> to add the SSL certificate path before starting it all up.</p>
<pre><code class="lang-plaintext">nginx.conf
</code></pre>
<pre><code class="lang-plaintext">http {
 server {
   listen              443 ssl;
   server_name         myapp.com;
   ssl_certificate     /etc/letsencrypt/live/myapp.com/fullchain.pem;
   ssl_certificate_key /etc/letsencrypt/live/myapp.com/privkey.pem;   charset utf-8;
   access_log off;
</code></pre>
<pre><code class="lang-plaintext">location / {
     proxy_pass http://myapp:8080;
   }
 }
</code></pre>
<pre><code class="lang-plaintext">}
events { worker_connections 1024; }
</code></pre>
<p>Copy the <code>docker.compose.yml</code> and <code>nginx.conf</code> onto the Droplet using Filezilla or a scp command.</p>
<pre><code class="lang-plaintext">scp docker-compose.yml root@{droplet_ip}:/myapp/docker-compose.yml
scp nginx.conf root@{droplet_ip}:/myapp/nginx.conf
</code></pre>
<p>Log on into the Droplet and run the containers</p>
<pre><code class="lang-plaintext">$ cd /myapp
$ docker-compose up -d
</code></pre>
<pre><code class="lang-plaintext"># check containers are up
$ docker ps
# view app logs
$ docker logs myapp
# view nginx logs
$ docker logs nginx
</code></pre>
<p>The service should now respond at <em>https://mydomain/test</em></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Check out the source code on <a target="_blank" href="https://github.com/gcatanese/1-2-3-SpringBoot-Docker-Nginx-DigitalOcean">GitHub</a></p>
<p>Another useful reference: <a target="_blank" href="https://www.digitalocean.com/docs/droplets/how-to/add-ssh-keys/">how to add a SSH key to your Droplet</a></p>
]]></content:encoded></item><item><title><![CDATA[1, 2, 3: Docker, Heroku, MongoDB Atlas, Python]]></title><description><![CDATA[This is a walkthrough explaining how to Dockerize and deploy on Heroku a Python application using MongoDB Atlas. Why 1–2–3? Focus on simple essential…]]></description><link>https://beppecatanese.hashnode.dev/1-2-3-docker-heroku-mongodb-atlas-python</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/1-2-3-docker-heroku-mongodb-atlas-python</guid><category><![CDATA[Docker]]></category><category><![CDATA[Heroku]]></category><category><![CDATA[MongoDB Atlas]]></category><category><![CDATA[Python]]></category><category><![CDATA[docker-registry]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Tue, 22 Dec 2020 11:00:00 GMT</pubDate><content:encoded><![CDATA[<hr />
<h3 id="heading-1-2-3-docker-heroku-mongodb-atlas-python">1, 2, 3: Docker, Heroku, MongoDB Atlas, Python</h3>
<p>This is a walkthrough explaining how to Dockerize and deploy on Heroku a Python application using MongoDB Atlas.</p>
<blockquote>
<p>Why 1–2–3? Focus on simple essential aspects, clear code samples and relevant references.</p>
</blockquote>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*foT3BHbi9d_c8eNxP2E4Iw.jpeg" alt /></p>
<hr />
<h3 id="heading-the-application">The Application</h3>
<p>It all starts with source code, of course, let’s create a Python app on top of the <a target="_blank" href="https://flask.palletsprojects.com/en/1.1.x/">Flask</a> framework.</p>
<p>The application provides a few REST endpoints and a DAO layer to access the database.</p>
<pre><code class="lang-plaintext"># app.py 
from flask import Flask, request, Response
import logging
import requests, import os

try:
    app = Flask(__name__)

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('werkzeug').setLevel(logging.ERROR)
except Exception as e:
    logging.exception("Error at startup")


@app.route('/ping')
def ping():
    """
    Ping the endpoint
    :return:
    """
    return "ping Ok"


def get_port():
    """
    Retrieves port for env variable
    :return:
    """
    return int(os.environ.get("PORT", 5000))


if __name__ == '__main__':
    app.run(debug=True, port=get_port(), host='0.0.0.0')
</code></pre>
<p>Verify you can run the application in your favourite IDE (PyCharm is mine) or from the command line (`<em>python app.py`</em>), it should respond to <a target="_blank" href="http://localhost:5000/ping">http://localhost:5000/ping</a></p>
<h3 id="heading-mongodb-atlas">MongoDB Atlas</h3>
<p>Sign up for MongoDB Atlas (if you do not have already an account) and set up your free MongoDB. It is straightforward following the Atlas step-by-step Wizard.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*ielULk_-cy_pJ8NG61uI8A.jpeg" alt /></p>
<p>In a nutshell, you will need to:</p>
<ul>
<li><p>create a cluster</p>
</li>
<li><p>create a DB user</p>
</li>
<li><p>allow incoming connections (edit firewall rules)</p>
</li>
<li><p>connect</p>
</li>
</ul>
<p>A common mistake is to forget to allow your IP address (step #3 above): enter your current IP address or allow them all if your repository does not store critical data (for example for this tutorial).</p>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*6qVy_PUQXLd2RPmm2OQ37A.jpeg" alt /></p>
<p>The final and most interesting step is to connect to the MongoDB Atlas from your Python application</p>
<pre><code class="lang-plaintext">#db_client.py
</code></pre>
<pre><code class="lang-plaintext">from pymongo import MongoClient
</code></pre>
<pre><code class="lang-plaintext">connect_string = 'mongodb+srv://{db_username}:{db_password}@devcluster.s4lc7.mongodb.net/{db_name}?retryWrites=true&amp;w=majority'
</code></pre>
<pre><code class="lang-plaintext">client = MongoClient(connect_string)
db = client.get_default_database()

# get user by name
def get_user_by_name(name):
    return db.user.find_one({"name": name})

# add new user
def add_user(name):

    ret = get_user_by_name(name)

    if ret is None:
        new_user = {"name": name}
        x = db.user.insert_one(new_user)
        ret = x.inserted_id

    return ret
</code></pre>
<p>The <code>connect_string</code> is hardcoded in the source code (don’t forget to replace the placeholders with the actual MongoDB username, password and DB name), this is done to simplify the example. You should really avoid that and instead, define the connection string (and any other configuration) as an environment variable.</p>
<h3 id="heading-docker-on-heroku">Docker on Heroku</h3>
<p>We have now a working application (you can add some unit testing too) and it is time to deploy.</p>
<p>The <a target="_blank" href="https://devcenter.heroku.com/articles/container-registry-and-runtime">Heroku Docker Registry</a> is a good solution to deploy your application for a few reasons:</p>
<ul>
<li><p>you build a generic image that can be deployed on other Docker runtimes</p>
</li>
<li><p>Docker images are not subject to size restrictions unlike deployment from git repositories (max 500MB)</p>
</li>
</ul>
<h4 id="heading-pre-requisites">Pre-requisites</h4>
<p>First, create a new Heroku application (using the Heroku CLI or the web interface) by choosing a good name ☺️</p>
<p>Secondly (and very importantly) log in to Heroku and in the Heroku Docker Registry</p>
<pre><code class="lang-plaintext">heroku login
heroku container:login
</code></pre>
<h4 id="heading-dockerfile">Dockerfile</h4>
<p>Here is the Dockerfile for our example, starting from the <code>python-slim</code> base image.</p>
<pre><code class="lang-plaintext">FROM python:3.9-slim

COPY app/ /app

EXPOSE 5000

WORKDIR /app
RUN pip install -r requirements.txt

ENTRYPOINT ["python"]
CMD ["app.py"]
</code></pre>
<h4 id="heading-build-push-release">Build, Push, Release</h4>
<p>Time to rock: let’s Dockerize the application and push it to Heroku. Note the image tag (registry.heroku.com) and the process type (web).</p>
<pre><code class="lang-plaintext"># build the image
docker build -t myapp .
# tag
docker tag myapp registry.heroku.com/myapp/web
# push
docker push registry.heroku.com/myapp/web
# release (when deployment starts)
heroku container:release web -a myapp
</code></pre>
<p>Check the logs to see it is really happening</p>
<pre><code class="lang-plaintext">heroku logs -a myapp
</code></pre>
<p>Invoke the <code>/ping</code> endpoint <a target="_blank" href="https://dockerherokumongotutorial.herokuapp.com/ping">https://myapp.herokuapp.com/ping</a></p>
<h3 id="heading-tadaaaa"><strong>TADAAAA!!!</strong> 😀</h3>
<h3 id="heading-config-vars">Config Vars</h3>
<p>The last step is to remove the hardcoded database connection string (naughty developers!) and use instead an environment variable.</p>
<pre><code class="lang-plaintext"># read env variable
def get_mongo_connect_string():
    return os.environ.get("MONGO_CONNECT_STRING", "")
</code></pre>
<p>In your local development environment is a good idea to create a <code>.env</code> file which is typically gitignored (never pushed to your source repository) and uses the Python <a target="_blank" href="https://pypi.org/project/python-dotenv/">.dotenv</a> package to load the values.</p>
<p>On Heroku, you want to define the environment variables as <a target="_blank" href="https://devcenter.heroku.com/articles/config-vars">Config Vars</a>: at deployment time Heroku will inject the variables (connection strings, tokens, secrets) in the Dyno provisioned for your application.</p>
<p><img src="https://cdn-images-1.medium.com/max/2400/1*6qvrYvThw35uhabCIAmmZw.jpeg" alt /></p>
<hr />
<h3 id="heading-conclusion">Conclusion</h3>
<p>I hope this is helpful for developers who start to work with Docker and Heroku: the focus is mainly on providing clear code and configuration examples as they are the best way to learn.</p>
<hr />
<p><strong>References</strong></p>
<p>Check out the walkthrough source code on <a target="_blank" href="https://github.com/gcatanese/1-2-3-Heroku-Docker-Python-MongoDB">GitHub</a></p>
<p>Docker Container Registry documentation on <a target="_blank" href="https://devcenter.heroku.com/articles/container-registry-and-runtime">devcenter.heroku.com</a></p>
<p>Best practices for creating Dockerfiles on <a target="_blank" href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/">docker.com</a></p>
]]></content:encoded></item><item><title><![CDATA[Tweesky: don’t miss the Twitter Card preview]]></title><description><![CDATA[There is (obviously) lots of sharing of resources and links on Social Media (that’s the idea!) but surprisingly the nice Twitter Link Preview does not…]]></description><link>https://beppecatanese.hashnode.dev/tweesky-dont-miss-the-twitter-card-preview</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/tweesky-dont-miss-the-twitter-card-preview</guid><category><![CDATA[social media]]></category><category><![CDATA[Twitter]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Mon, 05 Oct 2020 10:00:00 GMT</pubDate><content:encoded><![CDATA[<hr />
<p>There is (obviously) lots of sharing of resources and links on Social Media (that’s the idea!) but surprisingly the nice Twitter Link Preview does not always appear.</p>
<p>This is not a great situation when you are growing your follower base, promoting your blog post or simply wanting to look nice and professional.</p>
<p>All Twitter gurus out there agree: the visual impact of the nice Card Preview is a must.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*WCOU-YsfBnDBxgpxWheD1Q.png" alt /></p>
<p>Twitter Summary Card</p>
<hr />
<h3 id="heading-why-is-that">Why is that?</h3>
<p>The <a target="_blank" href="https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/abouts-cards">Twitter Card</a> preview relies on a few simple markup tags:</p>
<pre><code class="lang-plaintext">&lt;meta name="twitter:card" content="summary" /&gt;                
&lt;meta name="twitter:title" content="Beppe Catanese Github Home" /&gt;                &lt;meta name="twitter:description" content="Personal projects (Java, Python, Chatbots, Date Engineering" /&gt;                
&lt;meta name="twitter:image" content="https://avatars3.githubusercontent.com/gcatanese/..." /&gt;
</code></pre>
<p>Although there are a few more, those above are the essential ones that the web page must provide. If they are not found the fancy preview goes south.</p>
<h3 id="heading-how-do-i-fix-it">How do I fix it?</h3>
<p>The simplest and most logical way is to include the meta tags in the pages which are going to be shared on Twitter.</p>
<p>If you cannot do that (or don’t want to do it) then Tweesky comes to the rescue.</p>
<h3 id="heading-say-hello-to-tweesky">Say hello to Tweesky</h3>
<p><a target="_blank" href="https://twitter.com/tweesky_tk">Tweesky</a> is a little side project to work with Social Media, Python and metainformation.</p>
<p>Tweesky grabs a URL and provides an enriched tiny URL feature</p>
<blockquote>
<p>FROM <a target="_blank" href="https://github.com/gcatanese">https://github.com/gcatanese</a> TO <a target="_blank" href="https://tweesky_tk/abcd">https://tweesky_tk/abcd</a></p>
</blockquote>
<p><strong>Not another tiny URL thing!?</strong> Uhm.. yes, it does provide all of that, the link redirects the user to the original URL (without accessing or storing any user or browser information), but it also generates the necessary Twitter Tags from the information found on the Web page.</p>
<p>Tweesky lives on Twitter and is waiting for Direct Messages (DMs) from followers: if the DM contains (only) a link there is a reply with a Tweesky URL.</p>
<h3 id="heading-an-example">An example</h3>
<p>Let’s Tweet one of my Github projects: <a target="_blank" href="https://github.com/gcatanese/S3-Simple-Browser/blob/master/README.md">https://github.com/gcatanese/S3-Simple-Browser/blob/master/README.md</a></p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*k9lkclszN9Fo-9LG-dmWww.png" alt /></p>
<p>Preview of Github URL</p>
<p>Oopsy-Daisy, the basic information is there but there is no image :-(</p>
<p>Let’s see the corresponding Tweesky URL:</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*n35w2G8Ylp1AKBbfWJjQEg.png" alt /></p>
<p>What is happening? The original page has several meta tags but for some reason the image meta tag is incorrect. Often it is more the case that the page does not have the Twitter meta tags at all and it is using the <strong>OpenGraph</strong> attributes or the <strong>Schema Org</strong> data, both powerful protocols to provide meta information.</p>
<p>In these situations the Twitter Preview cannot always build a complete card, so Tweesky tries to go a step further and obtain the tags from whatever it is available (OpenGraph, Schema Org or the HTML tags).</p>
<h3 id="heading-notes-and-references">Notes and References</h3>
<p>A few remarks to consider:</p>
<ul>
<li><p>Twitter Card preview description does not appear on mobiles (viewport limitations?)</p>
</li>
<li><p>the Tweesky URL does not always render correctly in Twitter (I am not sure how/when the view is rendered or refreshed… still trying to figure it out): try to post the URL in a new Tweet or validate it with <a target="_blank" href="https://cards-dev.twitter.com/validator">Twitter Card Validator</a> tool</p>
</li>
<li><p>Tweesky cannot deal yet with <a target="_blank" href="https://en.wikipedia.org/wiki/Single-page_application">Single Page Application</a>: coming soon</p>
</li>
<li><p>Page screenshot is taken when no image is available in the meta tags</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Stepping into the Data Engineering world]]></title><description><![CDATA[I have completed the “Data Engineering Nanodegree” by Udacity and I thought I would share my experience. Like many other online providers, Udacity offers…]]></description><link>https://beppecatanese.hashnode.dev/stepping-into-the-data-engineering-world</link><guid isPermaLink="true">https://beppecatanese.hashnode.dev/stepping-into-the-data-engineering-world</guid><category><![CDATA[data-engineering]]></category><category><![CDATA[UdacityNanodegree]]></category><dc:creator><![CDATA[Beppe Catanese]]></dc:creator><pubDate>Wed, 02 Sep 2020 10:00:00 GMT</pubDate><content:encoded><![CDATA[<hr />
<p>I have completed the “Data Engineering Nanodegree” by Udacity and I thought I would share my experience.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*V9ZRc_Jb2kO4sb4xEmjaPA.jpeg" alt /></p>
<hr />
<p>Like many other online providers, Udacity offers video lessons (which you can follow whenever it suits you) complemented with quizzes, online workspaces for exercising and additional material (documentation and references).</p>
<p>There is an online community to seek help or exchange tips, a KnowledgeBase for technical (and non) questions and a dedicated mentor (more later…..).</p>
<p>The web-based portal is pretty good, you can resume a lesson at the point that was left and there is some extra material (introduction to Python or other libraries).</p>
<p>Every module terminates with an assignment (a few days to a week effort) to solve a data engineering problem with the concepts learned during the lessons.</p>
<hr />
<h3 id="heading-pre-requisites">Pre-requisites</h3>
<p>Knowledge of SQL and Python is required, ideally at an <strong>intermediate level</strong> at least: in every lesson there is data modeling and Python coding, if you struggle with those it is going to be a long painful journey.</p>
<p>Udacity bonus: some introductory material (Python Numpy and Pandas) is provided.</p>
<hr />
<h3 id="heading-1-welcome-to-the-nanodegree-program">1. Welcome to the Nanodegree Program</h3>
<p>Safely skip this. This an intro to the platform and Udacity Career Services (PLEASE!!). Seriously? We come here to learn, not to look for a job.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*2hMqvNs0w_J7co-uVix_aQ.png" alt /></p>
<h3 id="heading-2-data-modeling">2. Data Modeling</h3>
<p>A good start with a dive into data modeling with relational and NoSQL databases, covering important concepts like denormalization, star and snowflake schema, and also working with Postgres and Cassandra.</p>
<p>This block requires to deliver 2 projects: Data Modeling with Postgres and Data Modeling with Cassandra. Good stuff.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*UbdT2d_EU6n2ZaKFci-LZA.png" alt /></p>
<h3 id="heading-3-cloud-data-warehouses">3. Cloud Data Warehouses</h3>
<p>Another good one: designing a Data Warehouse using Amazon AWS computing, specifically Amazon Redshift and S3 Storage.</p>
<p>This is a juicy section: copy raw data from S3 into staging tables, and create a cluster to process the data following a Star Schema design. <code>Infrastructure-as-code</code>is also introduced with some clear examples.</p>
<p>PS. You are entitled to AWS free credits</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*UbdT2d_EU6n2ZaKFci-LZA.png" alt /></p>
<h3 id="heading-4-data-lakes-with-spark">4. Data Lakes with Spark</h3>
<p>Apache Spark (finally) turns up. The theory behind the tool, features and data wrangling are fine, but the practical part is disappointing.</p>
<p>There are neither clear instructions nor good examples on how to set up and run Apache Spark, some lessons have clear gaps which make the project quite hard. A big disappointment, especially considering that Spark was one of the attractive elements of this program.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*2hMqvNs0w_J7co-uVix_aQ.png" alt /></p>
<h3 id="heading-5-data-pipelines-with-airflow">5. Data Pipelines with Airflow</h3>
<p>Design, execute and debug pipelines on Airflow, that’s good, but mainly because the tool is amazing. Again the concepts are relatively well presented but there is not a lot of info on how to run Airflow rather than relying on the available workspace.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*A-UdzIqxVVmJyzjqhpJ1VA.png" alt /></p>
<h3 id="heading-6-capstone-project">6. Capstone Project</h3>
<p>The course closes with the final project where you are supposed to put into practice what you learned from day one. Datasets are made available and there are references to a few good sources. The project instructions are broad to ensure the student makes assumptions and justifies design decisions.</p>
<p>This was a frustrating experience because a lot of the effort has been put into configuring and running the actual tools rather than developing the ETL.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*A-UdzIqxVVmJyzjqhpJ1VA.png" alt /></p>
<h3 id="heading-dedicated-mentor">Dedicated mentor</h3>
<p>Another big letdown. I was looking forward to soaking up views and tips from an experienced data engineer, but it didn’t happen.</p>
<p>The first mentor cancelled a meeting at the very last minute and did not show up at another agreed time (always evening meetings), the second one did the same, so I decided to get along on my own.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*2hMqvNs0w_J7co-uVix_aQ.png" alt /></p>
<h3 id="heading-finale">Finale</h3>
<p>Overall, I would recommend it if you are keen on getting into the #dataengineering arena. Despite some pain and unnecessary effort the “nanodegree” covers all fundamentals and gives a good overview of the available toolset. It could be a better, but I guess this is true for everything (and everyone).</p>
<p><strong>Plus</strong></p>
<ul>
<li><p>Redshift</p>
</li>
<li><p>Online Jupyter Notebook workspaces</p>
</li>
<li><p>Portal usability</p>
</li>
<li><p>AWS credits</p>
</li>
</ul>
<p><strong>Minus</strong></p>
<ul>
<li><p>Spark examples</p>
</li>
<li><p>Personal mentor</p>
</li>
<li><p>Career services</p>
</li>
</ul>
]]></content:encoded></item></channel></rss>