<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Les Jackson on Medium]]></title>
        <description><![CDATA[Stories by Les Jackson on Medium]]></description>
        <link>https://medium.com/@les.jackson?source=rss-75cdcdfd6dbb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5apOrdQrDmlOYLQByNllXA.png</url>
            <title>Stories by Les Jackson on Medium</title>
            <link>https://medium.com/@les.jackson?source=rss-75cdcdfd6dbb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 20:46:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@les.jackson/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[14 Tips when integrating with GraphQL]]></title>
            <link>https://medium.com/@les.jackson/14-tips-when-integrating-with-graphql-14a30f518d83?source=rss-75cdcdfd6dbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/14a30f518d83</guid>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Les Jackson]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 23:45:34 GMT</pubDate>
            <atom:updated>2023-12-18T21:54:15.678Z</atom:updated>
            <content:encoded><![CDATA[<p>This quick guide introduces you to 14 tips that you should follow when building solutions that consume a GraphQL API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4EcousIoFuVi7kVaKWjiw.jpeg" /></figure><h3>1. Understand the basics 🧑‍🎓</h3><blockquote>Understanding the foundational basics of GraphQL will set you up for success in moving forward with your build.</blockquote><p>GraphQL is significantly different from other API design patterns, (e.g. REST), so you should familiarize yourself with the core concepts. The <a href="https://graphql.org/learn/">official GraphQL site</a> is a great place to start.</p><p>At a minimum you should be familiar with:</p><ul><li>What is a Graph (nodes &amp; edges)</li><li>Queries</li><li>Mutations</li><li>GraphQL Types</li><li>Pagination</li><li>Error responses</li><li>Authentication &amp; Authorization</li></ul><h3>2. Read the API Docs 📖</h3><blockquote>Knowledge is power! Familiarizing yourself with the specific API providers docs is critical if you want a low friction build.</blockquote><p>I know, I know — no one likes to read docs, it’s always more enticing just to jump in. However you will save yourself a lot of time and effort, (and that of any support teams that you need to contact), if you take some time to read (some of!) the documentation offered by the API provider.</p><p>Most providers, (Marketplacer include), usually provide a quick start guide for their APIs, these are a good place to begin.</p><h3>3. Pick the best-fit query or mutation 🧰</h3><blockquote>The right tool for the right job is a mantra used in many disciplines. Choosing the best fit query or mutation when building your solution is no different.</blockquote><p>Pick the correct tool for the job! There may be more than 1 way to query the data you need, however depending on your use-case 1 approach may be more suitable than the other, (this circles back to tip #2).</p><h4>Use-case</h4><p>I want to retrieve a single Product (aka GraphQL Object Type) from the API, should I:</p><ul><li>Use a query that can return multiple products, and apply filters to obtain the individual product</li><li>Use a node query that is designed just to return 1 Object type based on its ID</li></ul><p>The answer to this question may vary depending on whether you have access to the ID of the product, if you do, then a node query may be the best fit.</p><p>In the case of Marketplacer we offer a range of queries (in particular those related to Products), that have very different intended use-cases. Understanding the capabilities of these seemingly similar queries is important to building the best fit solution for your needs.</p><p>This idea extends to using something else other than the GraphQL API as well if it makes sense to do so. For example if you need near real-time updates on a products inventory position, you may be better placed to <a href="https://dev.marketplacer.com/docs/webhooks/webhooksoverview/">use a webhook</a> instead…</p><h3>4 . Provide variables as arguments 📥</h3><blockquote>Hard-coding values is never a good idea, indeed variables are usually one of the first concepts you learn about when starting out with software development — GraphQL is no different.</blockquote><p>Observe the following 2 queries that both retrieve an order with an ID of 12345:</p><pre># Recommended ✅<br>query GetOrder($id : ID!){<br>  node(id: $id)<br>  {<br>    ... on Order {<br>      __typename<br>      id<br>      totalCents<br>      createdAt<br>    }<br>  }<br>}<br><br># Not recommended ❌<br>query GetOrder{<br>  node(id: &quot;12345&quot;)<br>  {<br>    ... on Order {<br>      __typename<br>      id<br>      totalCents<br>      createdAt<br>    }<br>  }<br>}</pre><p>With the recommended approach you can see that we are passing the required order Id as a variable named $id (we need to populate this variable with the value 12345 when we call it).</p><p>Using variables has many advantages, not least: reusability, readability and supportability.</p><h4>One more thing…</h4><p>On top of the benefits that using variables bring, hardcoding values can have potential impacts on the syntactical integrity of the query. This is usually the case when the values are complex types or contain special characters.</p><p>Variables are definitely the way to go!</p><h3>5. Use pagination 📄</h3><blockquote>Pagination allows you to consume result sets in a manageable way, ultimately increasing the responsiveness of your queries and the scalability of your integration.</blockquote><p>The benefits of pagination are almost too numerous to mention, so much so that at Marketplacer we mandate its use when you can expect to return more than 1 result from a query. Benefits include, but are not limited to:</p><ul><li>Faster query response times</li><li>Scalability</li><li>Client memory usage</li></ul><h4>How it works</h4><p>Pagination allows you to retrieve a dataset by defining a page size (this is the maximum number of results permitted to be returned by each request). You then make requests to the API to obtain each “page” of data until you have processed the entire result set.</p><p>Each paginated <em>response</em> will typically identify:</p><ul><li>The total size of the result set</li><li>Whether there is another page of data to return</li><li>If using cursors, provide the cursor to allow you to move to the next page</li></ul><p>To see how we’ve implemented pagination at Marketplacer, <a href="https://dev.marketplacer.com/docs/operator-api/examples/utility/howto_paginate/">take a look at this guide</a>.</p><h3>6. Optimize Queries 🚀</h3><blockquote>With great power comes great responsibility. GraphQL gives you the power to tailor your queries to bring back the exact data you need — but do you <em>really need everything</em>?</blockquote><p>The following 2 issues with REST APIs were identified by the creators of GraphQL (Facebook), and it was largely in response to these issues that Facebook created GraphQL:</p><ul><li><strong>Over fetching</strong>: REST APIs often give you more data that you need (e.g. I just want the Product ID and Price, instead I get every attribute of a product)</li><li><strong>Under-fetching</strong>: REST APIs often require you to make multiple requests to different resource types to build the complete dataset you need</li></ul><p>The power of GraphQL is that you can tailor your queries to return just the data you need, this includes retrieving fields for nested / related objects:</p><pre>query GetOrder($id : ID!){<br>  node(id: $id)<br>  {<br>    ... on Order {<br>      __typename<br>      id<br>      totalCents<br>      createdAt<br>      invoices<br>      {<br>        nodes<br>        {<br>          id<br>          legacyId<br>          seller{<br>            businessName<br>          }<br>          lineItems{<br>            id<br>            variantId<br>            variantBarcode<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>In this query not only are we bringing back the Order object, but also the following objects:</p><ul><li>Invoices</li><li>LineItems</li><li>Seller</li></ul><p>Also as you can see we have selected only particular fields for each object — just the ones we need.</p><p>However, like any power, it can be abused: the more data you bring back, the larger the potential “cost” of that query, and the less optimal it becomes.</p><blockquote>When constructing your queries, think about the problem you’re solving and whether you really need all the data you are requesting.</blockquote><p>Optimizing queries is a bigger topic that just trimming the data you are requesting, and speaks also to the following concepts which are covered elsewhere in this guide:</p><ul><li>Use of pagination when returning lists of fields</li><li>Use of Fragments and Aliases to better structure your queries</li></ul><h3>7. Name all operations 📛</h3><blockquote>Naming your operations can assist with understanding the intent of the query or mutation, as well as being beneficial when debugging or tracing requests.</blockquote><p>The following 2 queries do exactly the same thing, however 1 is named and 1 is anonymous:</p><h4>What about pagination?</h4><p>Both queries below could return more than 1 result, therefore we should be using pagination, however to allow us to focus on the concept at hand we have omitted it in this instance…</p><pre># Recommended ✅<br>query GetInvoices{<br>  invoices {<br>    nodes {<br>      id<br>      legacyId<br>      createdAt<br>      seller {<br>        businessName<br>      }<br>      shipments {<br>        id<br>        dispatchedAt<br>      }<br>      lineItems {<br>        id<br>      }<br>    }<br>  }<br>}<br><br># Not Recommended ❌<br>query {<br>  invoices {<br>    nodes {<br>      id<br>      legacyId<br>      createdAt<br>      seller {<br>        businessName<br>      }<br>      shipments {<br>        id<br>        dispatchedAt<br>      }<br>      lineItems {<br>        id<br>      }<br>    }<br>  }<br>}</pre><p>As you can see from the recommended approach, we have a query named <em>GetInvoices</em>, while this may appear obvious in this case, more complex queries servicing more intricate use cases could have arguably more meaningful names.</p><p>Benefits of naming your operations (queries and mutations in this case) include:</p><ul><li>They clarify the intent of your operation</li><li>They allow you to combine more than 1 operation in single query document, (you can only have 1 anonymous query per document)</li><li>They assist with tracing and debugging, you can use the operation name to help identify your queries and mutations in traces, logs etc.</li></ul><h3>8. Use Aliases 🥸</h3><blockquote>Do you want to return fields using a different name? Want to query the same thing 2x but using different arguments? If the answer is yes, then use aliases.</blockquote><p>The following query returns an Advert object using the field names prescribed by the API:</p><pre>query ($id: ID!) {<br>  node(id: $id) {<br>    ... on Advert {<br>      id<br>      title<br>      externalId<br>      description<br>    }<br>  }<br>}</pre><p>Assuming we pass a valid value for <em>$id</em>, the we’d get something like this returned:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;node&quot;: {<br>      &quot;id&quot;: &quot;QWR2ZXJ0LTEwMDA5MjkwOA==&quot;,<br>      &quot;title&quot;: &quot;Mobile Phone&quot;,<br>      &quot;externalId&quot;: 2233668,<br>      &quot;description&quot;: &quot;Powerful phone&quot;<br>    }<br>  }<br>}</pre><p>Using aliases you can “rename” any of the selected fields, this renaming is then reflected in the response. The reworked query (using aliases) is shown below:</p><pre>query ($id: ID!) {<br>  node(id: $id) {<br>    ... on Advert {<br>      marketplacerId: id<br>      productName: title<br>      sys_id: externalId<br>      description<br>    }<br>  }<br>}</pre><p>The response would look as follows:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;node&quot;: {<br>      &quot;marketplacerId&quot;: &quot;QWR2ZXJ0LTEwMDA5MjkwOA==&quot;,<br>      &quot;productName&quot;: &quot;Mobile Phone&quot;,<br>      &quot;sys_id&quot;: 2233668,<br>      &quot;description&quot;: &quot;Powerful phone&quot;<br>    }<br>  }<br>}</pre><p>Here you can see that by using aliases we’re returning the same data, however the field names have changed.</p><p>We can extend the use of aliases when we want to return multiple sets of the same object, but based on providing different arguments. In the following example we are wanting to return the variants of an advert, but we want separate results for those that can be displayed, and those that cannot. The following example will <em>not work</em> as we cannot query variants twice:</p><pre>query ($id: ID!) {<br>  node(id: $id) {<br>    ... on Advert {<br>      id<br>      title<br>      description<br>      descriptionHtml<br>      variants(displayable: true) { ❌<br>        nodes {<br>          id<br>          barcode<br>          published<br>        }<br>      }<br>      variants(displayable: false) { ❌<br>        nodes {<br>          id<br>          barcode<br>          published<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>To get round this, that’s right you guessed it, we use aliases:</p><pre>query ($id: ID!) {<br>  node(id: $id) {<br>    ... on Advert {<br>      id<br>      title<br>      description<br>      descriptionHtml<br>      displayableVariants: variants(displayable: true) { ✅<br>        nodes {<br>          id<br>          barcode<br>          published<br>        }<br>      }<br>      nonDisplayableVariants:variants(displayable: false) { ✅<br>        nodes {<br>          id<br>          barcode<br>          published<br>        }<br>      }<br>    }<br>  }<br>}</pre><h3>9. Use fragments 🧩</h3><blockquote>Fragments allow you to break otherwise long, complex queries into more manageable sections that can be reused.</blockquote><p>In the following query we are <em>not using</em> fragments, (again I’ve omitted using pagination so we can focius on the concept at hand):</p><pre>query publishedProducts {<br>  advertSearch {<br>    adverts {<br>      nodes {<br>        id<br>        title<br>        description<br>        variants {<br>          nodes {<br>            id<br>            barcode<br>            published<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>However we may want to adopt a fragment to represent the <em>variant </em>fields we are interested in:</p><pre>query publishedProducts {<br>  advertSearch {<br>    adverts {<br>      nodes {<br>        id<br>        title<br>        description<br>        variants {<br>          nodes {<br>            ...VariantPartial<br>          }<br>        }<br>      }<br>    }<br>  }<br>}<br>fragment VariantPartial on Variant {<br>  id<br>  barcode<br>  published<br>}</pre><p>Here you can see we have implemented a fragment called <em>VariantPartial</em> to split-out the variant component from the main query.</p><p>As this was a fairly simple example, we’ve arguably made the query more complex than is needed, (you may not implement a fragment if this is all you were doing).</p><p>To make this a little more realistic (i.e. scenario whey you may use fragments) we can adapt the query to return both displayable and non displayable variants — this is similar to the example we saw in #8 where we introduced aliases, (indeed we continue to Aliases):</p><pre>query publishedProducts {<br>  advertSearch {<br>    adverts {<br>      nodes {<br>        id<br>        title<br>        description<br>        displayableVariants: variants(displayable: true) {<br>          nodes {<br>            ...VariantPartial<br>          }<br>        }<br>        nonDisplayableVariants: variants(displayable: false) {<br>          nodes {<br>            ...VariantPartial<br>          }<br>        }<br>      }<br>    }<br>  }<br>}<br>fragment VariantPartial on Variant {<br>  id<br>  barcode<br>  published<br>}</pre><p>This is a more realistic use of fragments given the benefits of reuse that we are seeing. Just imagine a query that’s considerably more complex, and fairly soon the benefits of fragments are very apparent.</p><h3>10. Understand and handle errors 😵</h3><blockquote>Errors happen — get over it! But we need to be able to handle those errors gracefully when they occur.</blockquote><h4>The use of HTTP</h4><p>Both REST and GraphQL are agnostic from the transport that can be used to drive them — i.e. there is no need to use HTTP with either REST or GraphQL. With that being said, the vast majority of both those API types run over HTTP, and it is with this view of reality that we move on to talking about errors.</p><h4>Differences with REST</h4><p>REST APIs (running over HTTP) typically make use of the underlying HTTP Status codes to convey either success or failure states of the request, for example:</p><ul><li><strong>201 Created</strong>: is usually returned when you create a resource using a POST request</li><li><strong>204 No Content</strong>: is often used when returning a success response from updating a resource using a PUT request</li><li><strong>404 Not Found</strong>: is used when the resource you are accessing is not found</li><li><strong>400 Bad Request</strong>: is used when the request if malformed</li></ul><p>The list goes on, however the main takeaway is that REST uses these codes to report on error (and success) conditions, they will also usually provide further information in the payload response.</p><p>But why are we talking about REST?</p><p>We have covered REST (albeit at a high level) as a primer for our conversation on GraphQL — it’s one of the differences between the 2 API types that often catches out developers experienced with REST, but new to GraphQL.</p><blockquote>As a rule: GraphQL APIs do not rely upon HTTP status codes to convey error conditions within their control.</blockquote><h4>Error Responses</h4><p>So how does GraphQL return error responses? For the purposes of this conversation GraphQL will <a href="https://graphql.org/learn/serving-over-http/#response">return error responses in an errors collection as part of the JSON payload response</a>.</p><p>The example below shows the JSON response when there is a syntactic error with the query we submitted:</p><pre>{<br>  &quot;errors&quot;: [<br>    {<br>      &quot;message&quot;: &quot;Field &#39;lowestPrce&#39; doesn&#39;t exist on type &#39;Advert&#39;&quot;,<br>      &quot;locations&quot;: [<br>        {<br>          &quot;line&quot;: 8,<br>          &quot;column&quot;: 4<br>        }<br>      ],<br>      &quot;path&quot;: [<br>        &quot;query ad&quot;,<br>        &quot;node&quot;,<br>        &quot;... on Advert&quot;,<br>        &quot;lowestPrce&quot;<br>      ],<br>      &quot;extensions&quot;: {<br>        &quot;code&quot;: &quot;undefinedField&quot;,<br>        &quot;typeName&quot;: &quot;Advert&quot;,<br>        &quot;fieldName&quot;: &quot;lowestPrce&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>Here you can see the <em>message</em> contains the nature of the issue at hand, which in this case was the misspelling of the field <em>lowestPrice</em>, (we submitted <em>lowestPrce</em>).</p><p>In another example, the mutation is well-formed, (syntactically correct), but there is some kind of issue with the processing of the request:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;orderCreate&quot;: null<br>  },<br>  &quot;errors&quot;: [<br>    {<br>      &quot;message&quot;: &quot;Validation failed: Count on hand must be greater than or equal to 0&quot;,<br>      &quot;locations&quot;: [<br>        {<br>          &quot;line&quot;: 2,<br>          &quot;column&quot;: 2<br>        }<br>      ],<br>      &quot;path&quot;: [<br>        &quot;orderCreate&quot;<br>      ],<br>      &quot;extensions&quot;: {<br>        &quot;variant_id&quot;: &quot;VmFyaWFudC05OTk4NA==&quot;,<br>        &quot;count_on_hand&quot;: {<br>          &quot;VmFyaWFudC05OTk4NA==&quot;: 1<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>In this particular scenario we were actually attempting to create an order where there wasn’t sufficient stock holding for the item we wanted to purchase. Again you would need to interrogate the <em>errors</em> collection to understand the nature of the error.</p><p>In both these cases we received a HTTP 200 OK response, the errors need to be interrogated via the payload.</p><p>The take-away point here is that you will need to handle errors in GraphQL in a potentially different way to that of REST based APIs.</p><h3>11. Adopt caching strategies 🗃️</h3><blockquote>Slow moving data by its nature does not change much — do you really need to request it again?</blockquote><p>This tip centers round understanding the nature of the data that you’re requesting via the API:</p><ul><li>Does it change rapidly — e.g. the stock position in a popular item</li><li>Does it move slowly — e.g. Enumeration values that you could use for filtering queries</li></ul><p>In the case of slow moving data it makes sense to cache that data client side and use it from there. Not only would this be faster, it just cuts down on unnecessary calls to the API. Indeed, in the case where API’s are rate limited, or have some other “cost” attached, this makes a lot of sense.</p><p>This tip really could apply to any type of API, (not just GraphQL), but it’s one that makes the list as it really is low hanging fruit.</p><h3>12. Use a GraphQL client 🔌</h3><blockquote>You can construct your GraphQL API calls as raw HTTP POST requests, but why make life difficult for yourself? There’s a range of GraphQL clients that do a lot of the heavy lifting for you.</blockquote><p>As mentioned previously, while GraphQL is agnostic from HTTP, it is usually implemented on top of it. Breaking that down further, calls to a GraphQL endpoint are really nothing more than HTTP POST requests with a specifically-formed request body.</p><p>You can of course choose to implement your solution by making calls in this way, but you’re doing yourself a disservice.</p><p>That’s where GraphQL clients come in.</p><p>Clients come in all shapes and sizes, with feature sets ranging from the relatively basic, to much more elaborate.</p><p>What they all share in common is the general goal of abstracting away from the user (in this case the developer) some of the lower-level nuances of making GraphQL calls work.</p><p>Features of GraphQL clients include, but are not limited to:</p><ul><li><strong>Code generation</strong>: Ingesting the self-documenting GraphQL schema some clients can generate language-specific implementations of GraphQL types.</li><li><strong>Error Handling</strong>: Provide a simplified, and consistent way to deal with errors — see #10 above</li><li><strong>Batching and deduplicating requests</strong>: This reduces the number of calls to the API, and is particularly beneficial if you are making multiple requests in a short period of time</li></ul><p>The client you choose will be driven by the programming language that you are using, so we can’t cover them all here — the point is that if you’re consuming GraphQL APIs, you should invest some time in learning to use a suitable client, and avoid the raw construction of calls.</p><h3>13. Stay informed about changes 🪵</h3><blockquote>APIs change, and in the case of GraphQL APIs this change is often more of a continuous evolution, as opposed to versioned releases.</blockquote><p><a href="https://graphql.org/learn/best-practices/#versioning">Versioning of GraphQL APIs</a> is less common than say with REST, so it’s important to understand that the schema you’re using can shift beneath your feet, (i.e. you don’t usually get a clean jump from 1 version to another).</p><p>However because GraphQL is self-documenting, (changes appear immediately in the schema exposed via introspection), you can stay across these changes easily. Indeed some GraphQL clients (see #12), assist with this.</p><h4>Deprecations</h4><p>One special mention in this change story is the ability in GraphQL to mark fields as having been <em>depreciated</em>. This means that the field in question has either been replaced by an alternative, (and is no longer needed), or it is just no longer needed!</p><p>It is at the discretion of the API provider how long they maintain deprecated fields, but the long-term strategy should always be eventual removal of those fields- another good reason to stay across the ever-evolving GraphQL API.</p><blockquote>In the case of Marketplacer, we monitor usage of deprecated fields, and would of course never remove any that were being used — this type of change is always carefully managed.</blockquote><h4>Change Logs</h4><p>Marketplacer, like many API providers, also provides a change log that details not just what the change is, but why the change was made, as well as the use-case for introducing. In short, the change log provides more context around the change.</p><p>We advise all consumers of our APIs to <a href="https://changelog.marketplacer.com/en">subscribe to our Change Log</a>.</p><p>In general, staying across the evolving changes of any API (GraphQL or otherwise) is critical in ensuring your integrations:</p><ul><li>Continue work!</li><li>Leverage any new, innovative features the provider has added</li></ul><h3>14. Play nice: fair use &amp; rate limits 📈</h3><blockquote>If rate limits and or a fair use policy exist then adhering to them is not so much “best practice” but a mandatory requirement.</blockquote><p>This one is a bit of a no-brainer, rate limits aren’t optional — you need to adhere otherwise the performance of your integration will suffer. Fair use policies are possibly a little more subjective and open to interpretation.</p><p>The point really is that you should make your integration as efficient as possible, indeed many of the tips we’ve already covered feed in to this idea:</p><ul><li>Understand the basics</li><li>Read the API docs</li><li>Pick the query or mutation that closest fits your use-case</li><li>Use pagination</li><li>Optimize queries</li><li>Understand errors (i.e. retrying certain error conditions is pointless and could generate redundant traffic if you do so)</li><li>Caching strategies</li><li>Use a GraphQL client</li></ul><p>Rate limits can change and could potentially become more aggressive, as can fair use policies, by ensuring that you don’t come anywhere near activating these, you place your integration in a more advantageous state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14a30f518d83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 ways to develop locally with webhooks]]></title>
            <link>https://medium.com/@les.jackson/3-ways-to-develop-locally-with-webhooks-822c7fc45c2a?source=rss-75cdcdfd6dbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/822c7fc45c2a</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[webhooks]]></category>
            <dc:creator><![CDATA[Les Jackson]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 04:14:28 GMT</pubDate>
            <atom:updated>2023-10-02T04:14:28.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBYgG7PJ2-PWPk4sdSMUbQ.jpeg" /></figure><p>Webhooks are a lightweight, open, and effective way to work with events generated by other systems, and most importantly (for me at least) they avoid the need to use polling.</p><p>Despite their many benefits, one drawback that I’ve encountered in working with webhooks is their inability to be routed directly to your local development machine.</p><p>In this article I discuss 3 ways that I’ve found useful in working with that constraint.</p><h3>A typical webhook set up</h3><p>Just to clarify the issue a little further, when setting up a webhook on a 3rd party system you typically provide information on:</p><ol><li>The “event” that you want to receive, e.g. new order created</li><li>The data to be sent, e.g. Order Id, Delivery Address, Order Amount etc.</li><li>Where you want the data sent to (the HTTP endpoint destination)</li></ol><p>It is this last point where you can become a little unstuck as a developer wanting to work with these events on your local machine — what destination do you configure in order to get events delivered to localhost?</p><blockquote>While there isn’t really a webhook standard, for the most part webhooks are typically implemented as HTTP POST requests with a JSON body payload sent to the consuming system (in this case your local machine).</blockquote><p>As an example, if I attempt to configure a webhook on <a href="https://dev.marketplacer.com/">Marketplacer</a> to send Invoice events to a localhost endpoint, I’d get the following response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*1mNLc7Eu-OmMFG6x_qOhWA.png" /><figcaption>Error configuring a localhost webhook endpoint</figcaption></figure><p>And while you may get a slightly different error on other platforms, the fundamental issue remains, the 3rd party platform cannot route webhook events to localhost…</p><p>The remainder of this article discusses how you can work within this (understandable) constraint.</p><h3>1. Fake it</h3><p>This one is a bit of a cheat actually, and you’ll probably groan when I describe it, but in all honesty it’s an approach I’ve used, and indeed continue to use…</p><p>To use this approach all you have to do is use a HTTP API client like Postman or Insomnia and simply make direct HTTP POST requests to your localhost development endpoint, essentially “faking” a real webhook request. (Clients like <a href="https://www.postman.com/">Postman</a> and <a href="https://insomnia.rest/">Insomnia</a> running locally on your development machine can make requests to localhost destinations).</p><p>In order to make this “fake” request as realistic as possible, you’ll need to ensure that you replicate it as close to the original webhook from the source system as you can. To do that you will need to:</p><ul><li>Generate a real webhook request</li><li>Receive that webhook request somewhere (I use <a href="https://webhook.site/">webhook.site</a> for this)</li><li>Examine the body payload and headers</li><li>Replicate that body and headers with your HTTP Client (e.g. Postman)</li></ul><blockquote>If you navigate to webhook.site you’ll be given a unique, routable HTTP POST endpoint that you can use when setting up your webhook. Then when you trigger a webhook, this will be received at your webhook.site endpoint and you can examine, and replicate this in Postman.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQB3-28qRSDhcduZNoujFg.png" /><figcaption>Webhook captured by webhook.site</figcaption></figure><p>While this method may be considered a bit of a “cheat”, I continue to use it when I’m in the early stages of development, even if I have the other methods (listed below) available to me. Some of the reasons for this are:</p><ul><li>You don’t actually have to trigger a webhook on the source system which can sometimes be time consuming.</li><li>You can easily manipulate the headers and body payload directly, again without having to generate an actual webhook event…</li></ul><p>While this option is useful in the early (and possibly later) stages of development, it doesn’t provide you with a true end to end integration experience. In that case, you’d need to look at 1 of the other options…</p><h3>2. Use an ingress app</h3><p>The 2nd method requires the use of an ingress, or tunnelling app, with the most well known of these being <a href="https://ngrok.com/">Ngrok</a>.</p><p>Ngrok (and similar apps such as <a href="https://github.com/localtunnel/localtunnel">Localtunnel</a>), provide you with a routable url that maps down to a localhost endpoint on your dev machine. This means that you can provide the routable url to the system generating webhooks, and those webhooks will eventually make their way down to your local machine, and more specifically the app you’re building.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*YuZOut1emjNXSZPK1f22Wg.png" /><figcaption>Simplified Ngrok architecture</figcaption></figure><p>The advantages of the this solution are:</p><ul><li>Very easy to set up (Ngrok &amp; Localtunnel are anyway)</li><li>Ngrok provides a decent free plan</li><li>You get “real” webhooks delivered to your app</li></ul><p>One of the potential downsides to this approach is of course the security considerations you may have in opening up a tunnel from your local machine to what is essentially a public endpoint. Depending on the industry you work in, or the organisation that you work for, using something like Ngrok may not even be an option available to you given the misgivings about potential security threats.</p><h4>Setting up Ngrok</h4><p>While the Ngrok <a href="https://ngrok.com/docs/getting-started/">documentation is clear and straightforward</a>, I thought it may be useful to provide some steps for you here in case you’re interested in checking it out.</p><ol><li>Sign up for an <a href="https://ngrok.com/">Ngrok account</a> and download the app.</li><li>[Optional] Claim your free persistent endpoint. This means that you can use the same endpoint url every time you use Ngrok (otherwise you’ll get a newly generated endpoint url when Ngrok starts…)</li><li>Configure your authentication token. This token is provided to you under your Ngrok account settings along with the command prompt that you need to issue in order to add it to the Ngrok config file:</li></ol><pre>ngrok config add-authtoken &lt;your auth token&gt;</pre><p>After that you can start Ngrok by specifying the port number of your local http endpoint, e.g.:</p><pre>ngrok http 8080</pre><p>This will start Ngrok with a <em>non-persistent</em> routable url, forwarding to: <a href="http://localhost:8080/">http://localhost:8080</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*dlPDn-tJpIezid7_Zd1HCg.png" /><figcaption>Ngrok routing to <a href="http://localhost/">http://localhost</a>:8080</figcaption></figure><p>This did not suit my use-case as I wanted to:</p><ul><li>Use my persistent routable url (see step 2 above)</li><li>Forward requests to a local <em>https</em> endpoint on port 8081 (so not just http)</li></ul><p>In order to do this, you can alter the parameters you supply to the Ngrok cli in the following way:</p><pre>ngrok http --domain=&lt;persistent-domain&gt; https://localhost:8081</pre><p>In this case webhooks can be sent to https://&lt;persistent-domain&gt; and will be routed to my local https endpoint on port 8081</p><p>Ngrok can be configured way beyond this, but for the most part this covers what I need. However, as previously mentioned, ingress apps like Ngrok and Localtunnel may not be an option open to you - in which case there’s another option that could be adopted…</p><h3>3. Use a proxy</h3><p>There are a few variations of this pattern, but it essentially relies upon you having access to a routable endpoint somewhere (the “proxy”) which receives (and stores) the webhook traffic from the source system. You then need to retrieve the stored webhook messages down to your local machine, and finally route them to your local app.</p><p>As you can imagine there are a number of ways that this could be achieved but I use the following architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*cGihulIpDxE-XarKXzaA8Q.png" /><figcaption>Using Azure Functions and Service Bus to route webhooks locally</figcaption></figure><p>This approach relies upon 3 components:</p><ol><li>An Azure HTTP Function</li><li>An Azure Service Bus</li><li>Service Bus subscriber</li></ol><blockquote>I have placed an <a href="https://github.com/binarythistle/Local-Webhook-Proxy">example project on GitHub</a> that you can use to get going with this architecture.</blockquote><p>We talk a bit more about these below.</p><blockquote>As you can see I happen to have a preference for Azure, but other public clouds will have comparable services that you could use if you wanted to implement this pattern.</blockquote><h4>Azure HTTP Function</h4><p>This acts as a routable HTTP endpoint that can be used to directly receive webhooks from the source system. In this case I’ve elected to “store” these webhook events on an Azure Service bus. So when the Azure Function receives a webhook event it places it immediately on to the Service Bus.</p><h4>Azure Service Bus</h4><p>The Azure Service Bus acts as both:</p><ul><li>The persistent (or semi-persistent) store for the webhook messages</li><li>The method of delivering those messages to a (local) subscriber</li></ul><p>In relation to the persistence of the messages, the Service Bus does provide this but only for a relatively short period of time (when I say <em>short</em>, I’m talking about a period of days, or possibly weeks). This is more than enough for our use case however.</p><h4>Service Bus Subscriber</h4><p>This can be any app that can subscribe to our Azure Service Bus and read the messages from it. In this particular case this app is (not surprisingly) a .NET console app that triggers every time a message is placed onto the relevant topic of the Service bus. This agent then forwards these messages to whatever localhost endpoint it’s been configured to.</p><p>This approach may seem like using a sledge-hammer to crack a nut, but it does work and has the following advantages:</p><ul><li>Corresponds to more closely to something you’re likely to see in an enterprise production environment</li><li>The use of a Service Bus brings with it all the advantages including, but not limited to: security, message routing, message persistence &amp; event driven delivery.</li></ul><p>The downsides of this approach are:</p><ul><li>Complexity. There are a few moving parts which makes the whole thing harder to configure, monitor and fault find than using something like Ngrok</li><li>Cost. While the actual cost of this solution with a few hundred or even a few thousand webhooks would be minimal, it does still come with cost attached to it.</li></ul><p>I did genuinely use this method recently when I was unable to use Ngrok (due to security concerns) so I know it works. However, for sheer ease of use, I’d always opt for the ingress option.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=822c7fc45c2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consuming Webhooks with Azure Service Bus]]></title>
            <link>https://medium.com/@les.jackson/consuming-webhooks-with-azure-service-bus-1a168fe494fe?source=rss-75cdcdfd6dbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a168fe494fe</guid>
            <category><![CDATA[marketplaces]]></category>
            <category><![CDATA[azure-service-bus]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[webhooks]]></category>
            <dc:creator><![CDATA[Les Jackson]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 00:17:30 GMT</pubDate>
            <atom:updated>2023-01-18T00:19:16.646Z</atom:updated>
            <content:encoded><![CDATA[<p>In my day to day role I talk a lot about how our customers can leverage webhooks to obtain near real-time updates on the data held in <a href="https://www.marketplacer.com/">Marketplacer</a>. And that’s the point — I talked a lot about it, but hadn’t actually implemented anything myself. So I thought it was about time that I did! In this article I take you through how I leveraged various Microsoft Azure services to consume webhook traffic. It’s written as a step by step tutorial so you can follow along and build a similar solution if you feel up to the challenge.</p><blockquote>The <a href="https://github.com/binarythistle/Consuming-Webhooks">code for this tutorial </a>is available on GitHub.</blockquote><h3>Some context</h3><p>So just before I jump into what I built, it’s probably worth just setting the scene. Marketplacer is a SaaS platform that allows online retailers to extend the range of products they sell, products that they don’t actually own. At its core we can visualise the primary data flows as follows:</p><figure><img alt="Primary data flows" src="https://cdn-images-1.medium.com/max/542/1*N98G6Ai8ZB-gnQ0zPQuRnA.png" /></figure><p>For the purposes of this article we are focused on how the Retailer can leverage the webhooks that Marketplacer provides for use-cases including, but not limited to:</p><ul><li>Sync of Order Data (e.g. has the order shipped, been cancelled etc.)</li><li>Sync of Inventory Data (the stock-holding of the product)</li></ul><p>For these use-cases we also have the following considerations:</p><ul><li>There may be a “large” number of sync events (e.g. “Click Frenzy” / “Black Friday” sales) would result in events for both orders and inventory.</li><li>Sync events need to traverse in as close to real-time as possible (we don’t want orders placed for products that we no longer have inventory for)</li><li>Sync events need to traverse reliably between parties, (we don’t want to lose events)</li></ul><p>As you will appreciate, these considerations are not restricted to our use-cases, and are in fact common considerations for most distributed applications.</p><h3>What we’ll build</h3><p>Below is the high-level use-case architecture we will simulate, (we’ll replace Marketplacer in our tutorial build):</p><figure><img alt="Reference Architecture" src="https://cdn-images-1.medium.com/max/1024/1*bKpDZRhSgC3LAc8bcn4kjg.png" /></figure><p>The solution components are as follows:</p><h4>Marketplacer Domain</h4><blockquote><strong>Note:</strong> you don’t need to have access to the Marketplacer platform to follow along with this tutorial, as we’ll be simulating the generation of webhooks. We’ve included Marketplacer here to illustrate our use-case only.</blockquote><ol><li><strong>Marketplacer GraphQL API.</strong> Would be used by the Online Retailer to create an order placed by the Customer.</li><li><strong>Marketplacer Webhooks</strong>. Following the creation of an order, a webhook would be generated from Marketplacer to the Inventory Endpoint.</li></ol><h4>Online Retailer Domain</h4><blockquote><strong>Note:</strong> this is where we will be doing all development, for the most part this will be on Microsoft Azure or in the case of the Variant Subscriber, our local machine.</blockquote><p>3. <strong>Inventory Endpoint. </strong>This is our HTTP POST endpoint that will receive webhooks from Marketplacer. In this case we are using Azure Functions.</p><p>4. <strong>Service Bus.</strong> I thought leveraging a Service Bus, (in this case Azure Service Bus) to act as an intermediary between our Inventory Endpoint (#3) and our Inventory Subscriber (#5) was a good idea from a reliability perspective. The Inventory Endpoint essentially just dumps the Webhook Payload on to the Service Bus for later consumption.</p><p>5. <strong>Inventory Subscriber. </strong>In this case I went for a simple .NET app running locally on my development machine, (we could of course have used another Azure Function). This application consumes messages from the service bus and writes them to the console log.</p><h3>Use case sequencing</h3><p>The use-case the steps are shown below, overlaid on our reference architecture:</p><ol><li>A Customer places an order on the Online Retailers Marketplace, which calls the…</li><li>The <strong>Marketplacer GraphQL API</strong>. When an order is created, the inventory position of the Product is changed, which will trigger an update event using…</li><li><strong>Marketplacer Webhooks</strong>. The webhook would send a HTTP POST request to…</li><li>The <strong>Inventory Endpoint</strong>. This Azure Function will receive the HTTP POST request, it will then place the message onto the relevant Topic on the…</li><li><strong>(Azure) Service Bus</strong>. Messages will queue here until picked up by the…</li><li><strong>Inventory Subscriber</strong>. The Inventory Subscriber reads messages from the Service Bus and writes them to the console.</li></ol><figure><img alt="Use case sequencing" src="https://cdn-images-1.medium.com/max/1024/1*qiNJlVNYIADmXgOLzhIAKQ.png" /></figure><h3>Build steps</h3><p>The build steps that follow take you through all the “Online Retailer ‘’ Domain services you need to build to consume webhooks. So that you can follow along with the tutorial, we’ll simulate the generation of webhooks, (as opposed to using Marketplacer), to that end we’ll provide 2 ways to simulate those webhooks in this tutorial:</p><ol><li>Manually using <a href="https://www.postman.com/downloads/">Postman</a></li><li>Automatically using <a href="https://k6.io/open-source/">K6</a></li></ol><p>A revised build architecture (when not using Marketplacer) is shown below, this is the architecture we’ll follow for the rest of the tutorial:</p><figure><img alt="Simplified build architecture" src="https://cdn-images-1.medium.com/max/905/1*dEfLEcciGrAS7o4mRpc6sQ.png" /></figure><h4>K6 Script</h4><p>Before using K6, you’ll need to make sure it’s installed, you can find instructions on how to install for your chosen OS here: <a href="https://k6.io/docs/get-started/installation/">https://k6.io/docs/get-started/installation/</a></p><blockquote>K6 is good choice here as it allows us to generate large amounts of webhook traffic easily, simulating (in this case), large order volumes that would have emanated from Marketplacer.</blockquote><p>To test your installation, type:</p><pre>k6 -v</pre><p>You should see something like:</p><figure><img alt="K6 version information" src="https://cdn-images-1.medium.com/max/474/0*mpGdCoi1DanRuGKl" /></figure><p>Next, well create a K6 script file to simulate the generation of webhook traffic directly to the Inventory Endpoint (we’ll create this later). So in your chosen working directory, create a file called <strong><em>webhook_gen.js</em></strong> and populate it as follows, (again you can <a href="https://github.com/binarythistle/Consuming-Webhooks/blob/main/K6/webhook_gen.js">get the code directly from GitHub</a>):</p><ol><li>VUS are “Virtual Users” so you can increase this number to simulate more users</li><li>I’ve specified that I want to use “iterations” — i.e. how many times do I want to call the endpoint. You can increase this number as required. An alternative to “iterations” is “duration”, this allows you to specify how many seconds you want the script to run.</li><li>This would be the URL or either a) the API you want to call, e.g. the Marketplacer create order API, or b) the direct URL of the Inventory Endpoint.</li><li>We are just sending a simple payload here, a JSON object with 1 key attribute “name” with a value of “James Bond”. We’ll make use of this later when we directly call our Inventory Endpoint. Of course this just nonsense example data we are using for the purposes of this tutorial.</li><li>Add any headers that you need to add.</li><li>The call to the endpoint</li><li>Response output</li></ol><figure><img alt="webhook_gen.js file" src="https://cdn-images-1.medium.com/max/611/0*mfCE32lWxKbAq096" /></figure><p>We’ll not run this just yet, but we’ll test with our Inventory Endpoint after we set it up next…</p><h4>Inventory Endpoint — Part 1</h4><p>As we’ll be building services in Azure it is assumed that you have an Azure account, I’d also suggest you use the Azure budgeting feature to monitor your spend — I can’t be held responsible for that!</p><p>After logging into Azure, select Create a Resource:</p><figure><img alt="Create a resource in Azure" src="https://cdn-images-1.medium.com/max/432/0*zBTiSfXJILEVh-Yo" /></figure><p>Search for “Function App” and Click “Create”</p><figure><img alt="Search for the function app in the Azure marketplace" src="https://cdn-images-1.medium.com/max/557/0*dYF-4IVJaQ-EqinB" /></figure><p>On the Create Function App Screen, populate the following fields as shown below:</p><ol><li>Select your subscription</li><li>Select your Resource GroupCreate a unique name for your Webhook Endpoint</li><li>Select Code (as opposed to Docker Container)</li><li>Select .NET as the runtime</li><li>Select 6 as the version of .NET</li><li>Select a region most appropriate for you</li><li>Select Windows as the Operating System</li><li>Select Consumption (Serverless) as the Plan Type</li></ol><figure><img alt="Create function app" src="https://cdn-images-1.medium.com/max/775/0*tt5LyCBmdV6Z0Dnp" /></figure><p>Then click Review and Create (the defaults for the other settings should suffice):</p><figure><img alt="Review and create" src="https://cdn-images-1.medium.com/max/272/0*TzuKxvwo7LJW2V_y" /></figure><p>Review your settings. Once you’re happy, click Create:</p><figure><img alt="Review your settings" src="https://cdn-images-1.medium.com/max/656/0*z0t6ehVbphAobNrK" /></figure><p>As usual, Azure will now proceed to spin up your Function App.</p><figure><img alt="Deployment in progress" src="https://cdn-images-1.medium.com/max/775/0*i2-r0Xf2VkmPZNZl" /></figure><p>Once complete, click on “Go to resource”</p><figure><img alt="Resource created" src="https://cdn-images-1.medium.com/max/456/0*AbHV00kUfDJCOmD4" /></figure><p>You will then be directed to the newly created Azure Function, noting that the function is running (#1), if you want to stop this at any time just click the stop button.</p><p>We now want to configure our functions on the app, to do so click “Functions” (#2).</p><figure><img alt="Inventory endpoint details" src="https://cdn-images-1.medium.com/max/698/0*Dn8-We85LvtaZM33" /></figure><p>Click Create (#1):</p><figure><img alt="Inventory endpoint functions" src="https://cdn-images-1.medium.com/max/606/0*tXe_IXJMfvxPltKC" /></figure><p>Select “VS Code” for the Development Environment (#1). You will then be provided with some contextual help around how to set up VS Code to create and write Azure Functions.</p><figure><img alt="Create a function" src="https://cdn-images-1.medium.com/max/877/0*xoWPO3mEcVgaS09N" /></figure><p>We’ll go through those steps next, before we move over to VS Code on our local development environment, be sure to click “Close” on the Create Function Page.</p><h4>Setting up VS Code to build Azure Functions</h4><p>To allow us to author and deploy Azure functions from within VS Code we need to do the following:</p><ol><li>Install the npm support packages for Azure Functions</li><li>Install the the Azure Functions extension for VS Code</li></ol><p>For the npm support packages you will need to have node / npm installed. The steps to do that are slightly outside the scope of this tutorial but I’m sure some quick Googling with show you the way.</p><p>To check that you have npm installed, type the following at a command prompt:</p><pre>npm --version</pre><p>This should return something along the lines of this:</p><figure><img alt="npm version returned" src="https://cdn-images-1.medium.com/max/592/1*s8DpywUC0aGlRRyrITlpxw.png" /></figure><blockquote><strong>Note:</strong> if you get some kind of error response here, make sure you have npm installed correctly before proceeding.</blockquote><p>Next we want to installed the npm support packages for Azure Functions, to do so type the following at a command prompt:</p><pre>npm install -g azure-functions-core-tools@4 --unsafe-perm true</pre><p>This should install the required packages.</p><p>Next we want to install the Azure Functions extension for VS Code. You can find this by clicking on the “Extensions” icon in VS Code (#1) and searching for “Azure Function” (#2). Then simply install the extension:</p><figure><img alt="Install Azure Functions extension" src="https://cdn-images-1.medium.com/max/979/1*L2Difiva0y3y0IoS4AHkbw.png" /></figure><h4>Creating a function</h4><p>Click on the Azure Extension in VS Code (#1) then click the small cross (#2) to add a function, make sure you select “Create Function…”:</p><figure><img alt="Creating an Azure Function in VS Code" src="https://cdn-images-1.medium.com/max/501/0*ReLaedyFZ5Ea2x2c" /></figure><p>We will need to create new Project to house our Azure Function code, click Create new project:</p><figure><img alt="Create new project dialog box" src="https://cdn-images-1.medium.com/max/308/0*KJ0QIOZdEsu_foEm" /></figure><p>Browse to the location where you want to create the project, (I created a folder called “Inventory Endpoint” to house my project):</p><figure><img alt="Inventory Endpoint location" src="https://cdn-images-1.medium.com/max/615/0*c9mvHpbA0Q1Sjwbc" /></figure><p>You will then be prompted in VS Code to select the language for the Azure Function, select C#:</p><figure><img alt="Select c# as the language for our function" src="https://cdn-images-1.medium.com/max/441/0*VQMbGkAHZZmGiK8U" /></figure><p>Next Select the .NET Runtime, we’ll pick .NET 6.0 LTS:</p><figure><img alt="Select 6.0 LTS as the version of the .NET framework we want to use" src="https://cdn-images-1.medium.com/max/463/0*WvLJf4XGbJRLoEDb" /></figure><p>Next select the template type for the function, we want this function to be a HTTP endpoint, so select HTTP Trigger:</p><figure><img alt="Http Trigger Function type" src="https://cdn-images-1.medium.com/max/538/0*xFdNsFo4UhWBn_wd" /></figure><p>Give the function a name, you can leave the default value, but I’m changing this one to “InventoryTrigger”:</p><figure><img alt="Naming our Http trigger method" src="https://cdn-images-1.medium.com/max/616/0*Fr2fJEQmFj4YvKdt" /></figure><p>Provide a namespace, (this can be anything you like):</p><figure><img alt="Optional: provide a namespace (or just use the default)" src="https://cdn-images-1.medium.com/max/550/0*l33ItWUcrL7dsQ4c" /></figure><p>Select “Function” for the access type:</p><figure><img alt="Set access rights to Function" src="https://cdn-images-1.medium.com/max/553/0*PqCkNAPcwWmk0a8g" /></figure><p>And finally select where you’d like to open your newly created project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*UtroUji5ASI-mnpw" /></figure><p>This will Open the project in VS Code for you. If you see an “Unresolved Dependencies” message, click “Restore” to correct the errors:</p><figure><img alt="Click Restore to resolve dependencies" src="https://cdn-images-1.medium.com/max/553/0*Owibyv2h5AjWWkK2" /></figure><p>We are now ready to code up our Azure Function.</p><h3>Azure Function code — Part 1</h3><p>The code for this function, as well as the other components and services can be <a href="https://github.com/binarythistle/Consuming-Webhooks">found on GitHub</a>.</p><p>Now that we have our Function App set up, before we start coding we just need to add the Azure.Messaging.ServiceBus package to the Azure Function project. To do so, bring up a terminal session (use CTRL + ` in VS Code to use the integrated terminal), and making sure you’re in the root of your project, then type:</p><pre>dotnet add package Azure.Messaging.ServiceBus</pre><p>If you look in the .csproj file for your project you should see the package reference:</p><figure><img alt="Package reference added to the .csproj file" src="https://cdn-images-1.medium.com/max/654/0*u0yxRR5Cfps3DMaZ" /></figure><p>Now move into the main code file for your function, as I called my function “InventoryTrigger”, I’ll be editing the InventoryTrigger.cs file.</p><p>At this point the template code just reads the HTTP request body and issues 1 of 2 responses depending on whether it can locate a JSON attribute called “name”.</p><p>We’ll update this code later to place the request body payload onto the Azure Service bus, for now we’ll just deploy our function to Azure and test it.</p><h4>Deploying to Azure</h4><p>In VS Code, make sure you have the Azure extension selected (#1), select the project workspace and click on “Deploy to Function App..” (#2):</p><figure><img alt="Deploying a function app" src="https://cdn-images-1.medium.com/max/540/0*hGyvZHRR4LWjPaoT" /></figure><blockquote>If you have not authenticated to your Azure subscription you will need to do so at this point.</blockquote><p>Select the Azure Resource where you want to deploy this code, (this is just the name of the Azure Function we created in the previous step):</p><figure><img alt="Select the Azure function deployment target" src="https://cdn-images-1.medium.com/max/466/0*rThHInK9pKR6-6MN" /></figure><p>You will be asked to confirm the deployment as this will overwrite any other code that this resources is using:</p><figure><img alt="Confirm the deployment target" src="https://cdn-images-1.medium.com/max/307/0*uyXJpFRVnP9UhBdT" /></figure><p>The deploy process will begin from within VS Code:</p><figure><img alt="Function being deployed to Azure" src="https://cdn-images-1.medium.com/max/836/0*r4PaNQAmVHeyqBIp" /></figure><p>The function should eventually deploy:</p><figure><img alt="Successful deployment of the function" src="https://cdn-images-1.medium.com/max/652/0*2vPy_zf1Q0fDV9_G" /></figure><h4>Obtaining the endpoint URL</h4><p>With our function deployed (don’t worry we’ll update the code to work with our Service Bus eventually), move back into the Azure Portal, and find our Azure Function, and select “Functions”:</p><figure><img alt="Obtaining the Fuction endpoint URL" src="https://cdn-images-1.medium.com/max/607/0*hmqjX-2pmnGPx9DF" /></figure><p>Then select the function we’ve just deployed:</p><figure><img alt="Select the Inventory Trigger function" src="https://cdn-images-1.medium.com/max/660/0*Irpg97akrALsIPa4" /></figure><p>Then select “Get Function Url”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*1H7ykpgVWaUOLhqn" /></figure><p>You can then copy the endpoint url as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*eEmyA3RS6LF83O3z" /></figure><h4>Testing the endpoint with Postman</h4><p>Open Postman and select: “New”:</p><figure><img alt="Create a new request in Postman" src="https://cdn-images-1.medium.com/max/464/0*JC-aje_2thcPLGaW" /></figure><p>Then select “HTTP Request”:</p><figure><img alt="Select HTTP Request" src="https://cdn-images-1.medium.com/max/458/0*8_S9vDsrxRNYK52C" /></figure><p>Then configure your request as follows:</p><ol><li>Select POST for the request type</li><li>Paste in your Azure Function URL</li><li>Select the Request “Body”</li><li>Select “Raw”</li><li>Select JSON</li><li>Enter the JSON object as shown</li><li>Finally click “Send”</li></ol><figure><img alt="Configuring your HTTP Request" src="https://cdn-images-1.medium.com/max/736/0*jIH91r_q2hXU2QMh" /></figure><p>Assuming everything worked as expected you should get the following message back from the function:</p><figure><img alt="HTTP 200 OK Returned from request" src="https://cdn-images-1.medium.com/max/725/0*I38JPPdTJU9GxbtB" /></figure><p><strong>Testing the endpoint with K6</strong></p><p>If you want to test your K6 set up with the function you can update your <em>webhook_gen.js</em> file as follows:</p><figure><img alt="Updated webhook_gen.js file" src="https://cdn-images-1.medium.com/max/596/0*7gR8HS9Vbv5SUomi" /></figure><p>To run, at a command prompt navigate to your webhook_gen.js flee and type:</p><pre>k6 run webhook_gen.js</pre><p>You should see output similar to the following:</p><ol><li>Response message from Azure Function</li><li>Number of Iterations</li></ol><figure><img alt="K6 run output" src="https://cdn-images-1.medium.com/max/986/0*J_LSaRXShjqhM4u9" /></figure><p>We’ll come back to our Inventory Endpoint later, but now we’ll move on to standing up our Service Bus.</p><h3>Azure Service Bus</h3><p>We now want to create the Service Bus that is going to act as an intermediary between our Inventory Endpoint that receives webhook traffic and the service that ultimately consumes the webhook traffic.</p><p>Back over in Azure, click Create a resource:</p><figure><img alt="Creating a resource in Azure" src="https://cdn-images-1.medium.com/max/432/0*sTpeTdmLGdTCV1Cb" /></figure><p>Search for “Service Bus”, and select the Azure Service Bus:</p><figure><img alt="Selecting the Service Bus resource" src="https://cdn-images-1.medium.com/max/542/0*TzqVqsOKw-HP7G4t" /></figure><p>Then click Create:</p><figure><img alt="Create the Service Bus" src="https://cdn-images-1.medium.com/max/599/0*2xvIUgUU5Jr9ExOA" /></figure><p>Then configure the Service Bus Namespace as required:</p><ol><li>Your Azure Subscription</li><li>The Resource Group</li><li>Unique name for your Service Bus</li><li>Location relevant to your region</li><li>Pricing Tier</li></ol><figure><img alt="Configuring the Service Bus resource" src="https://cdn-images-1.medium.com/max/788/0*uBlaBaeWl2gAWllh" /></figure><p>Pay special attention to #5, the Pricing Tier! For the purposes of this tutorial I’ve just picked the Standard as I want to make use of “Topics”.</p><p>You can choose to continue through the configuration wizard, but I’m just going to accept the defaults by selecting “Review + create”:</p><figure><img alt="Review and Create Service Bus" src="https://cdn-images-1.medium.com/max/504/0*iFlVt1irlrFYFiyj" /></figure><p>Review your settings:</p><figure><img alt="Review Settings" src="https://cdn-images-1.medium.com/max/581/0*Kzx443K1MnJvvp-C" /></figure><p>Then click create, Azure will then spin up your Service Bus:</p><figure><img alt="Service Bus deployment in progress" src="https://cdn-images-1.medium.com/max/763/0*y_VxxUgOlqFI4MQd" /></figure><p>When complete, go to your new Service Bus resource, and click add Topic:</p><figure><img alt="Create Service Bus Topic" src="https://cdn-images-1.medium.com/max/653/0*BWzsG775SJjmaO3r" /></figure><p>Call your topic whatever you like, I’m just going to use “Inventory”, (if you were using your Service Bus for multiple purposes you could have 1 Topic per purpose…), make sure you click create:</p><figure><img alt="Naming your Topic" src="https://cdn-images-1.medium.com/max/455/0*F-OZC9VD6M1sj0dK" /></figure><blockquote><strong>Note:</strong> You’ll need the name of your Topic later so make a note of it and put it aside for now.</blockquote><p>Once your Topic is created, select “Topics” from the left hand menu to see the list of Topics on your Service Bus:</p><figure><img alt="Listing topics" src="https://cdn-images-1.medium.com/max/617/0*U0YEW8X8nOa8wU3v" /></figure><p>Select your topic, and click add Subscription:</p><figure><img alt="Add a Subscription" src="https://cdn-images-1.medium.com/max/707/0*2iYJPLhMtTYVDful" /></figure><p>For the most part I accept the defaults with the exception of the 2 items listed below:</p><ol><li>A name for your Subscription</li><li>The Max delivery count — in this case I’ve just gone with 3</li></ol><figure><img alt="Subscription Details" src="https://cdn-images-1.medium.com/max/644/0*3kc_N8MG7_sc8gW3" /></figure><blockquote><strong>Note:</strong> You’ll need the name of your Subscription later, so make a note and put it aside for now.</blockquote><p>When done, click Create</p><p>When your Subscription has been created, navigate back to the Service Bus Namespace, and select 1) “Shared access policies”, then 2) “RootManageSharedAccessKey”</p><figure><img alt="Shared Access Policies" src="https://cdn-images-1.medium.com/max/628/0*JMAiaMS0pqwa0x8Q" /></figure><p>The pop up will allow you to select the Primary Connection string for this bus, copy this connection string and place it somewhere safe as we’ll need it later.</p><blockquote><strong>Note:</strong> It goes without saying that this connection string is highly sensitive and should be treated as such.</blockquote><figure><img alt="Connection String" src="https://cdn-images-1.medium.com/max/677/0*wHZWqJBIle9BwfFD" /></figure><p>At this point our Service Bus setup is complete. Let’s move on to our Inventory Subscriber.</p><h3>Inventory Subscriber</h3><p>The final piece of our setup is to create a very simple app that will consume our webhook messages from the service bus .</p><p>At a command prompt navigate to your working directory and create a new .NET 6 Console application as follows:</p><pre>dotnet new console -n InventorySubscriber</pre><p>After this has been scaffolded, change into the project directory (if you’re following with the examples above, it will be called InventorySubscriber), then type:</p><pre>code .</pre><p>This will open a new VS Code session hosting this project (assuming that you have VS Code installed of course!).</p><p>You should see something similar to this:</p><figure><img alt="Empty .NET console app" src="https://cdn-images-1.medium.com/max/883/0*FjFdfKofj_6L8922" /></figure><p>At the same command prompt “inside” the project folder, type the following to add the Azure Service Bus package:</p><pre>dotnet add package Azure.Messaging.ServiceBus</pre><p>This should add the following entry to your .csproj file</p><figure><img alt="Newly added package reference" src="https://cdn-images-1.medium.com/max/692/0*gSAPZiXaLNi_eklQ" /></figure><p>Move into the Program.cs file and remove any code that you find there and replace it with:</p><blockquote><strong>Note:</strong> this code is largely based on the Microsoft Docs that can be <a href="https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-how-to-use-topics-subscriptions">found here</a>.</blockquote><pre>using Azure.Messaging.ServiceBus;<br><br>ServiceBusClient client;<br>ServiceBusProcessor processor;<br><br>string connectionString = &quot;&lt;YOUR SERVICE BUS CONNECTION STRING&gt;&quot;;<br>string topicName = &quot;inventory&quot;;<br>string subscriptionName = &quot;S1&quot;;<br>int count = 0;<br><br>// handle received messages<br>async Task MessageHandler(ProcessMessageEventArgs args)<br>{<br>    count++;<br>    string body = args.Message.Body.ToString();<br>    Console.WriteLine($&quot;Received {count}: Message {body}&quot;);<br><br>    // complete the message. messages are deleted from the subscription. <br>    await args.CompleteMessageAsync(args.Message);<br>}<br><br>// handle any errors when receiving messages<br>Task ErrorHandler(ProcessErrorEventArgs args)<br>{<br>    Console.WriteLine(args.Exception.ToString());<br>    return Task.CompletedTask;<br>}<br><br>client = new ServiceBusClient(connectionString);<br><br>processor = client.CreateProcessor(topicName, subscriptionName, new ServiceBusProcessorOptions());<br><br>Console.WriteLine(&quot;----&gt; InventorySubscriber...&quot;);<br>Console.WriteLine(&quot;----&gt; Setting up Azure Service Bus Connection.&quot;);<br><br><br>try<br>{<br>    // add handler to process messages<br>    processor.ProcessMessageAsync += MessageHandler;<br><br>    // add handler to process any errors<br>    processor.ProcessErrorAsync += ErrorHandler;<br><br>    // start processing <br>    await processor.StartProcessingAsync();<br><br>    Console.ForegroundColor = ConsoleColor.Green;<br>    Console.WriteLine(&quot;----&gt; Connected!&quot;);<br>    Console.ResetColor();    <br><br>    Console.WriteLine(&quot;\nPress any key to end the processing&quot;);<br>    Console.ReadKey();<br><br>    // stop processing <br>    Console.WriteLine(&quot;\nStopping the receiver...&quot;);<br>    await processor.StopProcessingAsync();<br>    Console.WriteLine(&quot;Stopped receiving messages&quot;);<br>}<br>finally<br>{<br>    await processor.DisposeAsync();<br>    await client.DisposeAsync();<br>}</pre><p>If you’ve followed along with the tutorial, then the values for:</p><ul><li>topicName</li><li>subscriptionName</li></ul><p>Should be the same as what’s present in the code, however you will of course need to change these if not.</p><p>You will have to supply a value for connectionString, which we obtained in the last section.</p><p>So make the necessary changes, save the code, then at a command prompt “in” the project directory, just run up our subscriber with:</p><pre>dotnet run</pre><p>You should see something like this:</p><figure><img alt="Running Subscriber" src="https://cdn-images-1.medium.com/max/698/0*GCEU_kkzol38OkKI" /></figure><h3>Inventory Endpoint — Part 2</h3><p>To finish up our end to end example, we need to update the code in the Inventory Endpoint so that it can place messages onto the Service Bus. So back over in our InventoryTrigger project update the InventoryTrigger.cs file to reflect the following:</p><pre>using System.Threading.Tasks;<br>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.Azure.WebJobs;<br>using Microsoft.Azure.WebJobs.Extensions.Http;<br>using Microsoft.AspNetCore.Http;<br>using Microsoft.Extensions.Logging;<br>using Azure.Messaging.ServiceBus;<br><br>namespace OnlineRetailer.Webhooks<br>{<br>    public static class InventoryTrigger<br>    {<br><br>        static string connectionString = &quot;&lt;YOUR SERVICE BUS CONNECTION STRING&gt;&quot;;<br>        static string topicName = &quot;inventory&quot;;<br>        static ServiceBusClient client;<br>        static ServiceBusSender sender;<br><br>        private const int numOfMessages = 3;<br><br>        [FunctionName(&quot;InventoryTrigger&quot;)]<br>        public static async Task&lt;IActionResult&gt; Run(<br>            [HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, &quot;post&quot;, Route = null)] HttpRequest req,<br>            ILogger log)<br>        {<br><br>            log.LogInformation(&quot;C# HTTP trigger function processed a request.&quot;);<br><br>            string requestBody = await new StreamReader(req.Body).ReadLineAsync();<br><br>            client = new ServiceBusClient(connectionString);<br>            sender = client.CreateSender(topicName);<br><br>            using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();<br><br>            if (!messageBatch.TryAddMessage(new ServiceBusMessage(requestBody)))<br>            {<br>                // if it is too large for the batch<br>                throw new Exception(&quot;The message is too large to fit in the batch.&quot;);<br>            }<br>            //}<br><br>            try<br>            {<br>                // Use the producer client to send the batch of messages to the Service Bus topic<br>                await sender.SendMessagesAsync(messageBatch);<br>                Console.WriteLine($&quot;A batch of messages has been published to the topic.&quot;);<br>            }<br>            finally<br>            {<br>                // Calling DisposeAsync on client types is required to ensure that network<br>                // resources and other unmanaged objects are properly cleaned up.<br>                await sender.DisposeAsync();<br>                await client.DisposeAsync();<br>            }<br><br>            return new OkObjectResult(&quot;Inventory Webhook Payload Received&quot;);<br>        }<br>    }<br>}</pre><p>Save your code and deploy it to Azure as you have done previously.</p><p>We now have all the solution components in place to allow us to test end to end. To do this ensure:</p><ul><li>The changes to the Azure Function have deployed</li><li>The Inventory Subscriber is running</li></ul><p>I’m going to use K6 to simulate the firing of multiple webhooks. As noted below, I have updated some settings in the webhook_gen.js file:</p><figure><img alt="Re-run K6 to push traffic to the Inventory Endpoint" src="https://cdn-images-1.medium.com/max/354/0*8E6ilInVN8RucEH-" /></figure><p>In this case I’m going to call our Webhook Endpoint 100 times. Now at a command prompt, we’ll run our K6 script by typing:</p><pre>K6 run webhook_gen.js</pre><p>All things being equal this will pump 100 messages onto our endpoint, through our Service Bus, which will then be picked up by our subscriber!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a168fe494fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we measure GraphQL response times]]></title>
            <link>https://medium.com/@les.jackson/how-we-measure-graphql-response-times-627b87a4f3e3?source=rss-75cdcdfd6dbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/627b87a4f3e3</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Les Jackson]]></dc:creator>
            <pubDate>Wed, 05 Oct 2022 22:28:26 GMT</pubDate>
            <atom:updated>2022-10-05T22:28:26.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTXF4ASEq495hDnGlyae8w.jpeg" /></figure><p><em>“What response times can we expect from your GraphQL API?”</em></p><p>This is probably one of the most frequently asked questions we get at Marketplacer in relation to our GraphQL API. It’s a very reasonable question, and we understand why our customers ask it, but it’s not always that easy to answer…</p><p>In this article we share one of the approaches we’ve taken to benchmarking GraphQL API response times at Marketplacer.</p><p>But first, some background…</p><h4>The “<em>problem”</em> with GraphQL…</h4><p>The entire value proposition of the GraphQL design pattern, (for me anyway), is that:</p><ul><li>It avoids over-fetching</li><li>It avoids under-fetching</li></ul><p>Or to put it in another more positive way, you get exactly the payload response you want. The ability to write queries, and shape your payload to your exact needs is what makes it such an attractive proposition. To illustrate what I mean, let’s take a look at one of the queries we offer at Marketplacer: <em>advertSearch</em>.</p><blockquote>An “advert” in Marketplacer is really just a <strong>Product</strong>, but for various reasons I won’t go into here, we call them as “adverts” in the Marketplacer GraphQL API.</blockquote><p>AdvertSearch allows consumers of our GraphQL API to pull Products hosted in Marketplacer, through into whichever upstream system needs them. Two typical use-cases would be:</p><ul><li>To render a list of products in a search results page</li><li>To display a single Product Detail Page (or “PDP” in the land of eCom)</li></ul><p>These 2 uses-cases have different characteristics:</p><ul><li>The 1st requires multiple objects, but each with a “small” amount of data</li><li>The 2nd requires just 1 object, but with a “large” amount of data</li></ul><p>In both these cases you can use the <em>advertSearch</em> query to get this data, but is it safe to assume both queries would have similar response times? Er, no it would not…</p><p>This conundrum really brings us back to where we started, and the question: <em>“What response times can we expect from your GraphQL API?”</em> There isn’t really 1 answer…</p><h4>Query Profiles</h4><p>In order to attempt to answer the question around response times, we designed a number of “query profiles” that attempt to cover a range of common use cases.</p><p>We then run each of these query profiles at a regular cadence using <a href="https://k6.io/">K6</a>, (a very popular load testing framework), and capture the resulting data for subsequent reporting. This not only gives us a fairly decent response(s) to the aforementioned question, it also:</p><ul><li>Allows us to track responses times, over time</li><li>Easily introduce new profiles should our customers request them</li></ul><p>The current characteristics of our profiles include the following:</p><ul><li><strong>Query Depth:</strong> How many connections are we traversing in the query? This ranges from 1 up-wards. The “deeper” the query, the more costly it is, which may have impacts on response times</li><li><strong>Page Size:</strong> Requesting a maximum of 10- results per page as opposed to 1000 has implications for response times</li><li><strong>Filters:</strong> How many filters that are being applied with search-type queries.</li></ul><p>So for example, here are 2 query profiles for advertSearch, (we have many more but these are just 2 extreme examples):</p><ul><li>1-Level Depth / 10 Results Per Page / No Filtering</li><li>2-Level Depth / 1000 Results Per Page / 1x Filter</li></ul><p>As I’m sure you can imagine, the response time of the 1st query is lower than the 2nd one…</p><h4>Measurements Taken</h4><p>As mentioned we we use K6 as the primary vehicle to run tests, with each test being run with the follow parameters:</p><ul><li>Virtual Users (VUs): 1</li><li>Duration: 10s</li></ul><p>These can of course be changed, but for benchmarking purposes we feel this ok. We then gather the following metrics from the result of each test:</p><ul><li>Median Response Time</li><li>Average Response Time (averages are not great, but we capture anyway)</li><li>p(90): 90% of requests should be faster than the given latency</li><li>p(95): 95% of requests should be faster than the given latency</li></ul><blockquote>K6 has a much wider-range of metrics available, but again we just wanted to try to answer a simple question, in the simplest way possible…</blockquote><h4>Final Thoughts</h4><p>As mentioned in the introduction, we employ some complimentary approaches to measuring GraphQL response times, however this technique gives us a well-defined set of tests that make point in time comparisons fairly easy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=627b87a4f3e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>