<?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 Flowlet on Medium]]></title>
        <description><![CDATA[Stories by Flowlet on Medium]]></description>
        <link>https://medium.com/@Flowlet?source=rss-647fcad7514------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vWivrBrGrfrnm8QMgzIKwQ.png</url>
            <title>Stories by Flowlet on Medium</title>
            <link>https://medium.com/@Flowlet?source=rss-647fcad7514------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:13:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Flowlet/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[Hosting a static NextJS export on S3 and CloudFront with dynamic routes and API endpoints]]></title>
            <link>https://medium.com/@Flowlet/hosting-a-static-nextjs-export-on-s3-and-cloudfront-with-dynamic-routes-and-api-endpoints-13be082498e3?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/13be082498e3</guid>
            <category><![CDATA[lambda-edge]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 11:19:49 GMT</pubDate>
            <atom:updated>2023-01-18T11:19:49.108Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide will explore how to host a static website built with NextJS on S3, using CloudFront and Lambda@Edge. This configuration allows for fast and efficient delivery of your website’s content while providing a platform for building and hosting your API routes using Flowlet. It is an ideal setup for a website with both static and dynamic content. We will walk through the process of deploying your NextJS app to S3, configuring CloudFront to route requests, and using Flowlet for API routes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvJfJnvQxG4_ROuyzh_hrg.png" /></figure><h3>What do we get from the next export?</h3><p>NextJS’s export feature generates HTML files for all pages defined in the pages directory. However, when it comes to dynamic routes, such as those for user-generated content, we need to use the getStaticPaths and getStaticProps methods.</p><h3>Dynamic paths known on build time</h3><p>First, the getStaticPaths method lists all pages when they are known on build time. Below is an example for /pages/blog/[...path].tsx using <a href="https://www.contentlayer.dev/">Contentlayer</a>.</p><pre>import { allBlogs } from &#39;contentlayer/generated&#39;;<br>export async function getStaticPaths() {<br>  // List all paths and strip off the &#39;/blog/&#39; part.<br>  const paths = allBlogs.map(post =&gt; ({ params: { path: post.path.split(&#39;/&#39;).slice(2) } }));<br>  return {<br>    paths<br>  };<br>}<br>export async function getStaticProps(context) {<br>  const blog = allBlogs.find(post =&gt; post.path == &#39;/blog/&#39; + context.params.path.join(&#39;/&#39;));<br>  return {<br>    props: {<br>      path: context.params.path,<br>      blog<br>    }<br>  };<br>}<br>const BlogsPage = ({ blog }: { blog: Blog }) =&gt; {<br>  return &lt;section/&gt;;<br>};<br>export default BlogsPage;</pre><p>Note that you must include both the path and component parameters in getStaticProps.</p><p>Running next export will produce an HTML file per blog post.</p><h3>Dynamic paths for user-generated and other dynamic content</h3><p>When content continuously changes, we cannot run a deployment on every change. Yet, we still need to implement the getStaticPaths method to get at least one exported HTML file. We may define a dummy page and accept loading all content client-side. It would help if you didn&#39;t do this for SEO-relevant content, but it&#39;s acceptable for pages only visible to authenticated users.</p><p>The idea behind this approach is to define one path in getStaticPaths that uses a wildcard to represent all possible user-generated content IDs. In getStaticProps, we then return empty data for these IDs. This allows the exported HTML files to contain a single page that can load the accurate data client-side using the actual IDs. To implement this approach, we first define the dynamic route in our pages directory, using a parameter in the file name to represent the ID of the user-generated content. For example, a route for a blog post might be defined as pages/blog/[id].js, we implement the following methods:</p><pre>export async function getStaticPaths() {<br>  return {<br>    paths: [{ params: { id: &#39;@id&#39; } }]<br>  };<br>}<br>export async function getStaticProps(context) {<br>  return {<br>    props: { query: { id: &#39;&#39; } }<br>  };<br>}</pre><p>This change will result in an exported page at blog/@id.html.</p><p>Finally, in our component file, we can use the id parameter and useEffect hook to fetch the data client-side and display the user-generated content on the page. This approach allows us to handle user-generated content while still taking advantage of NextJS&#39;s export feature to create a fast, statically-generated website.</p><h3>Routing dynamic paths with Lambda@edge</h3><p>The result from next export contains &quot;.html&quot; suffixes and wildcards for dynamic paths. For routing these, we will use a Lambda@edge function to handle the &quot;.html&quot; suffixes and wildcards.</p><p>After running the next export command, we will generate a router-paths.txt file that lists all the exported pages. This file is added to the export and used by the Lambda function to map the incoming request&#39;s path to the correct HTML file on S3. This approach allows for dynamic routes while still leveraging the benefits of a static site.</p><p>The commands for creating a release are:</p><pre>npx next build<br>find out -name &quot;*.html&quot; | sed -E &#39;s:out/(.*):\1:g&#39; &gt; out/router-paths.txt<br>AWS s3 sync --delete out s3://BUCKET_NAME/</pre><p>You need to replace BUCKET_NAME with the name of your S3 bucket. Now is a good time to create it. Head over to the <a href="https://s3.console.aws.amazon.com/">AWS S3</a> console and click on &quot;Create bucket&quot;. Choose a name and region. The region is preferably close to most visitors, but choose whatever you wish. We will read it only from CloudFront and Lambda@edge functions, both running worldwide. You can leave all other settings as-is, including the &quot;block all public access check&quot;. Run the commands above after creating the bucket to fill it with the static export.</p><p>Now create a Lambda function from the <a href="https://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1">Lambda console</a>. Create this function in the North Virginia region (“us-east-1”). That is a requirement for Lambda@edge. Ultimately, it will run on the edge close to the user, but this region is used for deployments.</p><p>Click on “Create function” and select “Author from scratch”. The Lambda function uses the NextJS 18.x runtime. Expand the “Change execution role” fieldset and select “Create a new role with basic Lambda permissions”.</p><p>After you’ve created the function, replace the empty index.mjs with <a href="https://gist.github.com/mauritsl/18b1333b3891236f53644c1909b3b735">this gist for the routing Lambda</a> and replace the S3_REGION to the region where your S3 bucket is located (should be something like &quot;us-east-1&quot; or &quot;eu-west-1&quot;). Also, replace the S3_BUCKET_NAME with the name you chose.</p><p>Go to “Permissions” at the function settings and look up the execution role. Click on it to go to the role configuration. Now add the “AmazonS3ReadOnlyAccess” permission. The Lambda function needs this to read the router-paths.txt file from the bucket.</p><p>To test the function, create a test event with the following JSON code:</p><pre>{&quot;Records&quot;: [{&quot;cf&quot;: {<br>  &quot;request&quot;: {<br>    &quot;Uri&quot;: &quot;/blog&quot;<br>  }<br>}}]}</pre><p>Make sure to use a path that exists. The test output should give a response like</p><pre>{<br>  &quot;Uri&quot;: &quot;/blog.html&quot;<br>}</pre><p>The response path is the file we need to fetch from the S3 bucket. You may also test this with dynamic paths. When all goes well, go to the “Versions” tab and click on “Publish new version”. Then click the “Copy ARN” button to get this function’s (version-specific) ID. We need this ID for the CloudFront configuration in the next section.</p><h3>Setting up CloudFront</h3><p>To set up a CloudFront distribution, we first need to go to the CloudFront console and click on “Create Distribution.” In the “Origin” section, we select our S3 bucket as the origin and give our distribution a name. We choose also “Redirect HTTP to HTTPS” for the viewer protocol policy and save.</p><p>We need to explicitly allow CloudFront to access the S3 bucket because all public access to the S3 bucket is blocked. Set the “Origin access” field to “Origin access control settings”. Click on “Create control setting” to create a new config. Also, a blue box appears that informs you about the bucket policy. Click the “Copy policy” button and the “Go to S3 bucket permissions” link to set this config in the bucket.</p><p>Next, we go to the “Origins” tab and add an origin to handle API requests. We give it the origin domain “WORKSPACE.flowlet.app” and save it. Then, we go to the “Behaviors” tab. We need to create three behaviors to handle different types of requests. The first behavior is for static assets that can be directly fetched from S3. The second behavior is for dynamic pages that must use the Lambda function we created earlier. The third behavior is for API requests that must use the Flowlet origin.</p><p>Edit the default behavior created automatically and, under “Function associations”, provide the ARN for the Lambda function for “Origin request”. Also, create a new behavior with the path pattern “/./” that uses the S3 origin but no Lambda function. Then we create the behavior with path “/api/*” with the Flowlet origin, allowing all HTTP methods in its config. We set the Cache policy to “CachingDisabled” and the Origin request policy to “CORS-CustomOrigin”. The latter determines which headers are passed to the origin.</p><p>Once all the settings are done, we wait for the deployment to finish (we can see the status on the distribution overview page) and go to the distribution domain name (on the same page) to test if we can access our website.</p><h3>Using a custom domain</h3><p>This section will discuss how to use our domain name for the CloudFront distribution instead of the default “cloudfront.net” subdomain. To do this, go to Route53 and create a new hosted zone for our domain. We updated the nameservers for our domain to use the nameservers provided by Route53.</p><p>Next, we request a new TLS certificate with AWS Certificate Manager. We edit our CloudFront distribution, set the custom domain name, and link the certificate we just created. Then, we add an A and AAA record in Route53 and set it as an alias to the CloudFront distribution. If it doesn’t show up in the suggestions, it indicates something is wrong with the configuration. Likely the custom domain name is not set.</p><p>After propagating the DNS changes, we can test our site on our custom domain.</p><h3>Fixing the Permission Denied errors for 404 pages</h3><p>CloudFront will return an ugly permissions error if you go to a page that doesn’t exist. The reason for this 403 is that S3 returns a permission denied error for unknown objects. The ListObjects permission is required to know if an object exists, but the policy doesn’t have that. However, there is no valid reason for 403 errors here. We can fix it at the “Error pages” tab in the CloudFront distribution settings. Set a custom page for both 403 and 404 errors, for example, to /404.html. You should override the HTTP status code for 403 errors and set it to 404 because that is the valid response code for the visitor.</p><h3>Build an API-first web application</h3><p>In conclusion, this blog post has provided an in-depth guide on how to host a static website built with NextJS on S3, using CloudFront and Lambda@Edge. We have shown how to use Flowlet as the dev and hosting platform for the API routes of the website while using S3 to host the static assets.</p><p>By following this guide, you will have a fully functional, scalable, and fast website that can easily handle static and dynamic content. You can use this setup to build an API-first website.</p><p>Want to create your API-first web application using Flowlet?</p><ul><li><a href="https://flowlet.app/register">Get started with a 7-day trial</a></li><li>Follow us on <a href="https://flowlet.app/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13be082498e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 Things You Can Do with the Airtable API]]></title>
            <link>https://medium.com/@Flowlet/7-things-you-can-do-with-the-airtable-api-4e7caf800e8d?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e7caf800e8d</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[airtable]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 13:13:37 GMT</pubDate>
            <atom:updated>2022-12-22T13:13:37.728Z</atom:updated>
            <content:encoded><![CDATA[<p>Airtable provides a neat interface to view and edit your data. Depending on your needs, you might use it as the primary data source for your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWPxyY0gIc8IUYJY7_FOwA.png" /></figure><p>Although Airtable provides automation, but their possibilities are limited compared to what a low-code platform can do. Furthermore, the number of executions is limited, even for paid plans.</p><p>This post will show how to perform the basic CRUD operations, write comments, read attachments, and use webhooks with Airtable.</p><h3>Authentication</h3><p>We need to set up authentication before we can use the API. AirTable comes with two token types; personal access tokens and OAuth tokens (plus user tokens, but those are deprecated). Personal access tokens are usually the best choice if you just want to connect with your own AirTable account. You can use them to perform all CRUD operations, but you cannot add comments or use webhooks with such tokens. According to their docs, you should be able to, but these calls result in permission errors. Setting up OAuth is explained later in this post. For now, you’ll get away with a personal access token.</p><h3>Creating a personal access token</h3><p>You can create a personal access token from your <a href="https://airtable.com/account">Airtable account page</a>. The secret key is provided once, after which you have to store it in a safe place. Throughout this post, we assume that you have stored it in a Flowlet secret. To do so:</p><ol><li>Go to the Settings section in your Flowlet workspace.</li><li>Click the Secrets tab and add a secret of the type “Password”.</li><li>Give it the name “airtable” and paste the secret in the password field.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*uc346PR_L1JZR0WNN_gcHA.png" /></figure><h3>Reading table records from the Airtable API</h3><p>Airtable provides the <a href="https://airtable.com/developers/web/api/list-records">list records</a> endpoint to read rows from a table. A simple curl command is provided as an example, which is replicated below for reference.</p><pre><br>curl &quot;https://api.airtable.com/v0/{baseId}/{tableIdOrName}&quot; \<br>-H &quot;Authorization: Bearer YOUR_TOKEN&quot;</pre><p>This guide uses curl only for setting up webhooks, so you probably don’t need it to continue. Otherwise, you might want to learn more about it in our <a href="https://medium.com/@Flowlet/14-essential-cli-tools-for-working-with-apis-f02d9621ae2">post on CLI tools</a>.</p><p>Several query parameters are available to specify the number of rows and fields returned or to filter the rows. We will get to them later, but let’s test this call first.</p><p>There are three parameters that you need to replace. The easiest way to get the baseId and tableId is to go to the table in the Airtable interface. The URL looks like the example below:</p><pre>https://airtable.com/appQdymUzauE3QcNz/tblryynEqL4RRBP2C/viwfuYLsObB2xUMZ2</pre><p>This URL is formatted as follows:</p><pre>https://airtable.com/{baseId}/{tableId}/{viewId}</pre><p>So, the baseId is appQdymUzauD3QcNd, and the tableId is tblryynEqL8RRBP2C for this example. You may look at the first three letters to check your ids. They start with “app” for the base and “tbl” for tables.</p><p>To perform the API call in Flowlet, create a new re-usable flow and drag the loose pin labeled “in” to add an HTTP-request block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*WYSisPOz7u16h4r24Q1ULQ.png" /></figure><p>A new dialog comes up where you need to specify the input for the HTTP request. We’ll enter the URL in the text field on the bottom left. These fields are in JavaScript or JSON format, so be sure to enclose the URL with quotes, as seen in the screenshot below. Also, drag the pin aside from the next empty text field to the “secret” pin on the right. A dropdown appears right of the text field where you can select the value “airtable”. Providing the secret will add your personal access token to this request. There is no need to specify the authorization header manually, and you can keep this configuration free of confidential values. After entering all the details, the configuration will look like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*HQxG_uyY2sQTlLci7bK0Kg.png" /></figure><p>We can already test this API call. Click the “Test flow” button on the top right and click on “Run flow”. The HTTP request block will light up green if it runs successfully. Furthermore, a new icon appears on that block. Click it to inspect its input and output. You will see the data from Airtable here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*eatfwvB3EmuHWC3hON9EMg.png" /></figure><p>Furthermore, a half-transparent block with a sparkles icon appeared entitled “Validate”. That is a suggestion. You can click on the sparkles icon wherever you see it to accept a suggestion. In this case, it will transform into a normal block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiOGfpHGXOZjjFh-eHy8xw.png" /></figure><p>You should always validate responses of external systems, even when it comes from a well-known API. The reason for this is twofold. First, check for erroneous responses (API might be down or misbehaving). Secondly, defining the response type allows you to use the data quickly in the flow. After accepting the suggestion, click on the config icon of the validate block and choose “Edit schema”. You’ll see that a schema was already generated from the API response. That’s also why you see the suggestion only after running the flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*gjqkCHCumj2vLFu0PvnI2Q.png" /></figure><p>Drag the “valid” pin of the validate block to continue building your flow. You might loop over the returned records, for example.</p><h4>Reading attachments</h4><p>If you have attachments in the records, you’ll notice that the field value is an array with some details per attachment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*VvQVInu1tPY7l0buYKs5qQ.png" /></figure><p>The URL shown in the response does not require authentication. However, this link is valid for only two hours, so you have to download it when you need it later.</p><h3>Add a table record using the Airtable API</h3><p>Use the <a href="https://airtable.com/developers/web/api/create-records">create records</a> endpoint to add a row. Just like the “list records” endpoint (see above), this page shows an example using curl. The URL is identical, but this time the POST method is used, and new records are passed in via the post body. The format for this is similar to what you got back from “list records”, so you might use that as an example.</p><p>In Flowlet, the request looks like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*TQPz3CwvZ1n6Vs9x4FSGng.png" /></figure><p>Note that “title” and “description” here refer to column names in Airtable. The provided fields must match the names that you see in Airtable. Empty fields may be omitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*tgqLBifnohTfcJaxGNcY1A.png" /></figure><p>If you test the flow and take a look at the debug output, you’ll notice that Airtable returns a list of the created records amended with a newly generated id. You may not need this data, but if you want to use it in the flow, add the suggested validate block described earlier in this blog. For example, you can store the id to update this record later on.</p><h4>Adding attachments</h4><p>The Airtable API does not provide a way to upload attachments directly. Instead, you must provide a URL where Airtable can download the file. This may, or may not be an easy task, depending on the source of the attachment. An example post data with attachment is:</p><pre>{<br>  &quot;records&quot;: [{<br>    &quot;fields&quot;: {<br>      &quot;title&quot;: &quot;Regular field value&quot;,<br>      &quot;image&quot;: {<br>        &quot;url&quot;: &quot;https://example.com/image.png&quot;<br>      }<br>    }<br>  }]<br>}</pre><h3>Update a table record</h3><p>Airtable provides two endpoints to update records; <a href="https://airtable.com/developers/web/api/update-record">update record</a> for updating a single record and <a href="https://airtable.com/developers/web/api/update-multiple-records">update multiple records</a> for bulk operations. We’ll use the former in this post.</p><p>The URL is similar to what we’ve seen when reading and adding records, but with an added recordId. You can obtain this identification number in two ways. First, it’s returned from the list records or add record endpoint. Otherwise, you can get it from the Airtable interface after opening a record. The URL contains all required ids. The segment starting with “rec” is the record id, for example, recdkSI5Zv9x878eU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*cMh65pAsVDKJ9-9GAaCDYw.png" /></figure><p>You have to choose between two HTTP methods; PUT or PATCH. The former puts the provided data in this record without merging anything. The latter will keep fields not provided in the API call. In this example, we will set a single field and use the PATCH method.</p><p>The format for the post body of the bulk operation is identical to the format we have used to add a row. For the “update record” endpoint, however, you provide a single item from the “records” array. In Flowlet, this call looks like this:</p><p>The output contains all fields for this record, even when not provided in a PATCH request.</p><h3>Delete a table record</h3><p>Deleting a row is done with the same API call as an update but with the DELETE method and no request body. You may refer to the Airtable documentation for the <a href="https://airtable.com/developers/web/api/delete-record">delete record</a> endpoint.</p><p>There is not much that you will find in the output. To catch errors, you simply use the “error” pin. The flow continued here when the record was not found or when you did not have permission to delete the record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*Z7JcqbhT1xea_Q-DsStgdA.png" /></figure><p>You will receive the exact error in the debug output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*CtdYyf-TYY7KuKcqrvokUw.png" /></figure><h3>Setting up OAuth with Airtable</h3><p>Some operations are available only with OAuth access tokens. Setting up OAuth requires a few extra steps compared to personal access tokens. However, Flowlet’s generic OAuth integration takes the burden out of this process. You may review the blog post on <a href="https://medium.com/@Flowlet/connect-oauth2-apis-with-flowlet-secrets-4d39db4e90d5">connecting with OAuth2 APIs</a> first. This post will explain this process only briefly.</p><p>To get started, go to <em>Settings</em> &gt; <em>Secrets</em> in your Flowlet workspace and add a secret of the type “OAuth2”. Give it the name “airtable-oauth” — or any other name you haven’t used yet — and take note of the Redirect URL shown in this dialog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQyp44WnLVyKivCvZ7WWeQ.png" /></figure><p>Before completing this form, register your application at the <a href="https://airtable.com/create/oauth">Airtable developer portal</a>. You are asked to provide a name and <em>Redirect URL</em> in the first step. Provide any name and copy over the URL that Flowlet provided. When proceeding, you are given a <em>Client ID</em> and the option to generate a <em>Client Secret</em>. Paste both details in the Flowlet dialog.</p><p>Furthermore, you have to check the permissions you will use (or all if you are not sure yet). You need to provide the scope as well in the Flowlet secret. The value is space-separated here, so if you have checked all permissions, then the value for scope is:</p><pre>data.records:read data.records:write data.recordComments:read data.recordComments:write schema.bases:read schema.bases:write webhook:manage</pre><p>The last details you will need are the authorization and token endpoint. For Airtable, these are:</p><pre>https://airtable.com/oauth2/v1/authorize<br>https://airtable.com/oauth2/v1/token</pre><p>Save the secret and click on “manage tokens”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*6NG4Rci1dsN-OEV1PIxonA.png" /></figure><p>No token is available yet, but you can authorize Flowlet with your Airtable account by clicking the “Request access token” link. You should now see a page where you can authorize Flowlet. Click on “Add a base” before the “Authorize” button enables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*ZLfWTBuuqX0HaEBmh4Adlg.png" /></figure><p>In case of an error, you will return to Flowlet without seeing this page. Double-check the client id, client secret, and scope settings if this happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*AOXlDH7TF4Mv_felu-CunQ.png" /></figure><p>An access token is available after you’ve successfully authorized Flowlet. The token expires quickly after it was requested and hence might show that it is expired. This is not an issue since Flowlet will automatically request a new access token using the refresh token when needed.</p><p>You are now ready to make API calls using OAuth. Also, note that you can use this OAuth secret instead of the personal access token for all API calls described earlier in this post.</p><h3>Add a comment using Airtable’s API</h3><p>The <a href="https://airtable.com/developers/web/api/create-comment">create comment</a> endpoint is designated for this task. Its URL is similar to the update record action, but with “/comments” appended. The post body is an object with only the “text” attribute, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*FXbjhSwJilDpxn9yz9R4jA.png" /></figure><p>Make sure that you use an OAuth secret, as a personal access token will currently not grant the required permission.</p><p>When defining the post body, you may use backticks to enclose multiline strings. This is a standard JavaScript feature but not present in JSON. Also note that you can use mentions, as seen above. These are visible in Airtable as mentions, but you will not currently get a notification for this.</p><h3>Use AirTable’s webhooks to listen for changes</h3><p>At the time of writing, Airtable does not provide a user interface to manage webhooks. You need to create webhooks using an API call, and you need to authenticate using OAuth for that. Furthermore, we found complexities in Airtable’s webhook implementation not commonly found in other webhooks. Due to this nature, this section is more extensive and technical than any of the actions described above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*7KoxUL_OjPkGBQ3ALPZeXA.png" /></figure><p>As with any webhook, we create an HTTP request flow using the POST method. Also, check the “save requests to log” checkbox. In this example, we will use the path “/webhooks/airtable”, but you may use any path you prefer. After saving the configuration, shortcut the request pin to the response pin of the output block. You do not have to provide any tangible output, but the effect is that Flowlet responds with a 200 OK instead of an error code. An error response will instruct Airtable to repeat the same webhooks regularly until it gives up.</p><p>Now we need to enable this webhook in Airtable. As said, we have to use an API call for this, for which we have the <a href="https://airtable.com/developers/web/api/create-a-webhook">create webhook</a> endpoint. According to the docs, this should work with personal access tokens, but these are rejected now. Before we continue, set up the OAuth secret as described above. That allows you to grab an access token using the “manage tokens” link on the secrets page. Click on “Renew access token” to request a new token when the token is expired. Also, you need a base id and table id. Refer to the “reading table rows” section to learn how to obtain them. You now have everything to complete the curl example listed in the Airtable docs.</p><p>The curl example contains a key named “recordChangeScope”. Its value is a table id, so you will need to replace that one as well. Aside from replacing the tokens, you may also append “| jq” to the command for pretty output (only if you have jq installed). Below is an example of the complete API call using curl:</p><pre>curl -X POST &quot;https://api.airtable.com/v0/bases/appQdymUzauE3QcNz/webhooks&quot; \<br>-H &quot;Authorization: Bearer ACCESS_TOKEN&quot; \<br>-H &quot;Content-Type: application/json&quot; \<br>--data &#39;{<br>    &quot;notificationUrl&quot;: &quot;https://WORKSPACE.flowlet.app/api/webhooks/airtable&quot;,<br>    &quot;specification&quot;: {<br>      &quot;options&quot;: {<br>        &quot;filters&quot;: {<br>          &quot;dataTypes&quot;: [<br>            &quot;tableData&quot;<br>          ],<br>          &quot;recordChangeScope&quot;: &quot;tblryynEqL4RRBP2C&quot;<br>        }<br>      }<br>    }<br>  }&#39; | jq .</pre><p>The output for this command is similar to the one below.</p><pre>{<br>  &quot;id&quot;: &quot;achA8ctcRcIw0XsRi&quot;,<br>  &quot;macSecretBase64&quot;: &quot;lB4G/e....&quot;,<br>  &quot;expirationTime&quot;: &quot;2022-12-27T15:38:49.315Z&quot;<br>}</pre><p>The expiration time is seven days later. Airtable will not call your webhook URL after this date unless you refresh this webhook. The <a href="https://airtable.com/developers/web/api/refresh-a-webhook">refresh webhook</a> endpoint is available to do so. Set up an automated task flow in Flowlet to perform this call daily (because the interval between weekly tasks might be slightly more than a week). Add an HTTP request block for this call, set the method to POST, add the OAuth secret, and set the URL to “<a href="https://api.airtable.com/v0/bases/%7BbaseId%7D/webhooks/%7BwebhookId%7D/refresh%60">https://api.airtable.com/v0/bases/{baseId}/webhooks/{webhookId}/refresh</a>”. The webhookId is the <em>id</em> you received when creating the webhook.</p><p>Now that we have set up the webhook with Airtable, it is time to see what is coming in. Change a record in Airtable and then go to the logs in your Flowlet workspace. If all goes well, you will see a log similar to the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*VWZuptQ_O7MQF05ekVaR3A.png" /></figure><p>There isn’t much data to find here. In contrast, most webhook providers send the relevant details with the webhook. Airtable, however, sends a ‘ping’ to let your system know something has happened. To find out what that is, we must perform another API call to get the actual payload, which is what the <a href="https://airtable.com/developers/web/api/list-webhook-payloads">list webhook payloads</a> endpoint is for. If you implement this request and add the validate block, then you will find out that its response has the following format:</p><pre>{<br>  &quot;payloads&quot;: [<br>    {<br>      &quot;timestamp&quot;: &quot;1970-01-01T00:00:00Z&quot;,<br>      &quot;baseTransactionNumber&quot;: 123,<br>      &quot;actionMetadata&quot;: {<br>        &quot;source&quot;: &quot;string&quot;,<br>        &quot;sourceMetadata&quot;: {<br>          &quot;user&quot;: {<br>            &quot;id&quot;: &quot;string&quot;,<br>            &quot;email&quot;: &quot;info@example.com&quot;,<br>            &quot;permissionLevel&quot;: &quot;string&quot;,<br>            &quot;name&quot;: &quot;string&quot;,<br>            &quot;profilePicUrl&quot;: &quot;https://example.com&quot;<br>          }<br>        }<br>      },<br>      &quot;payloadFormat&quot;: &quot;string&quot;,<br>      &quot;changedTablesById&quot;: {<br>        &quot;tblryynEqL4RRBP2C&quot;: {<br>          &quot;changedRecordsById&quot;: {<br>            &quot;recThgNXwZIlzxBsw&quot;: {<br>              &quot;current&quot;: {<br>                &quot;cellValuesByFieldId&quot;: {<br>                  &quot;fldSb6Ir03ItQMmcv&quot;: &quot;string&quot;<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>  ],<br>  &quot;cursor&quot;: 123,<br>  &quot;mightHaveMore&quot;: true,<br>  &quot;payloadFormat&quot;: &quot;string&quot;<br>}</pre><p>Take care when accepting the suggestion for the <em>Validate block</em> here because the schema will include the record id that differs per request. To fix this, edit the schema and click on the “generate or import” link. Change the id to “…” and click the generate button.</p><p>The response does contain not only the payload for the last action but also previous calls. There is nothing in the ping request that you can use to filter this list (the timestamp from the ping is usually a few seconds after the payload). It complicates the processing because we have to keep track of what we have already processed. Furthermore, new items are added to the bottom of the list, so we need to use the cursor to fetch more items.</p><p>Processing the payloads gets complicated at this point. At least we need a Flowlet table to keep track of the processed payloads. It might be easier to continue in a script here. In Flowlet, scripts are written in TypeScript, and you should fully type their input and output. The debug dialog can help create the type definitions. Click the copy icon three times to copy the data as a TypeScript definition. Using this feature, and with the help of Airtable’s documentation, we came up with a <a href="https://gist.github.com/mauritsl/94f62b0324a60a9293b6b8c5ecd1a372">type definition for the webhook payloads</a>, which we extended to a <a href="https://gist.github.com/mauritsl/7d47ca55562f38813827ef5f0baacd70">script that filters processed payloads</a>. The script needs the base id, webhook id, and secret name (of the OAuth2 secret). Also, a table named AirtableWebhook is used to store the processed payloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*MtRrrJdxSmErUTzT3jynJQ.png" /></figure><h3>Integrating Airtable in your application</h3><p>Airtable’s REST API is straightforward for basic CRUD actions. Flowlet can integrate with this API reasonably easily using the standard HTTP request blocks and with the help of built-in authentication mechanisms.</p><p>Can’t wait to connect APIs with Flowlet?</p><ul><li><a href="https://flowlet.app/register">Get started with a 7-day trial</a></li><li>Follow us on <a href="https://medium.com/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e7caf800e8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mail Custom Images Using a Glide App Webhook and Robolly Rendering]]></title>
            <link>https://medium.com/@Flowlet/mail-custom-images-using-a-glide-app-webhook-and-robolly-rendering-649271db42bd?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/649271db42bd</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[robolly]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[glide]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 20:39:14 GMT</pubDate>
            <atom:updated>2022-12-22T16:27:47.929Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s use case we will send custom images upon a webhook triggered by an app created in <a href="https://www.glideapps.com/">Glide</a>. With the help of <a href="https://robolly.com/">Robolly</a>, we can easily customize images and send them along with mail messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4dUqzlx33Szox5rZKs2aQ.png" /></figure><h3>Setting up the Glide app</h3><p>You’ll need to <a href="https://go.glideapps.com/">create a new account on the Glide website</a> to get started. We started with one of the suggested templates and added a button somewhere. You can add this after clicking on the plus button in the left sidebar, aside from the header reading “screen”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*9KsDDwFxbxhe3Ukkhy0F5w.png" /></figure><p>After the button is added, you will be able to select an action in the right sidebar. Choose “Trigger Webhook” and add a URL. Use the URL https://WORKSPACE.flowlet.app/api/glide-webhooks/button, where WORKSPACE is replaced with your Flowlet workspace name. You may change the part after /api/, as long as you use the same path when configuring the flow later on.</p><p>A webhook accepts custom parameters. In our example, we’ll add “name”, “mail”, “text”, and “image”, but you can send whatever suits your needs. If everything is set up, you will end up with something similar to the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxyKXIdWS-SvpSvxmmRqBw.png" /></figure><h3>Catching the webhook in Flowlet</h3><p>Glide shall send a webhook request on each button click, but we will want to see that in action. First, create a new HTTP endpoint flow in your workspace. Click the configuration button on the top right of the start block and click on “Configuration”. A dialog comes up with various options for your HTTP endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*Kg2Q2_JAck5qiU7VI-xJBQ.png" /></figure><p>Set the method to POST. Almost all webhooks use the POST method, so it’s a sensible guess even without reading Glide’s documentation. Also, check the “Save requests to log” button and save the configuration. That feature provides a convenient way to test requests made by other systems (Glide in this case).</p><p>Now that a simple flow is ready go back to Glide and hit the button where the webhook is configured. It still does not give us a heads-up, but we can go back to Flowlet and take a look at the logs, accessible from the sidebar. You’ll see the incoming webhook showing up if everything is configured well. It is possible to inspect the posted values when you click on it or hit the red “Test flow” button to go to the flow debugging interface. From there, you can run the flow again with the same input and see what happens. Not much yet, actually, but we’ll quickly connect it with Robolly to create an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*NTQLl-pBbDFVzw6WgRi57A.png" /></figure><p>Now that you can see what Glide is sending to us, you may copy the contents (note the copy icons after all JSON elements) and use it to generate the post body scheme in the HTTP endpoint configuration. Use the “Generate or import” link in the configure dialog.</p><p>Paste the JSON and hit the “Generate” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*cqhdiq0ijOEdcZYI3p2gCg.png" /></figure><p>This configuration tells Flowlet which values we can use from the post body. We’ll see later how this is used.</p><h3>Exploring Robolly</h3><p><a href="https://robolly.com/">Robolly</a> is a powerful image rendering tool that can be used to create custom images for your email and social media campaigns. It lets you easily add text, logos, and other images to your templates with just a few clicks. After signing up, you’ll have the possibility to clone an example template. We used the “Bewildered tweet Horizontal post”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJREpvYEXOP4jlcsZHbX2A.png" /></figure><p>At the “Render” tab, you’ll find some render links. We will use the “Render link with modifications”, which looks like this:</p><pre>https://api.robolly.com/templates/TEMPLATE_ID/render.jpg?tweet=TEXT&amp;name=NAME&amp;image=URL</pre><p>The parameters differ per template, but the general concept is the same.</p><h3>Connecting Glide with Robolly</h3><p>Let’s generate the image with Robolly when clicking the button in the Glide app. The logic action here is to request the URL above when a webhook request comes in. Go back to the HTTP endpoint flow in Flowlet. Here, the right side of the start block has the label “request” and a loose endpoint. Now, drag that endpoint to an empty space on the screen. A new dialog titled “Add block” shows up. Search for “HTTP request” and add it. After you do that, another dialog appears that allows you to specify the input for the HTTP request block, based on the input of the webhook. We can complete the link between Glide and Robolly here, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*Do5soUrZj9sf3Yzo91QDDw.png" /></figure><p>Note that the “Scripted inputs” on the bottom left contain JSON values; hence the URL is enclosed with quotes. Otherwise, you will get an error when pressing “Save”. You may also use TypeScript in these fields, but it’s not required for this example.</p><p>After the HTTP request is configured, you may hit the “Test flow” button from the logs and then the “Run flow” button to test it. The blocks turn green if they run correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*tigPRzJiEPcJD-qzcW3Ysg.png" /></figure><p>Furthermore, a new button on these blocks lets you inspect the input and output per block. For the HTTP request block, you should see that it comes back with some image data, which is base64 encoded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*83KIt5PT4OT2gD3ARdfZtg.png" /></figure><p>We have to post the image data somewhere to make it visible. The next step will send it as a mail attachment.</p><h3>Sending emails over SMTP</h3><p>You have to bring your own SMTP server if you want to send mail from Flowlet. You may use your own mail account (Gmail, for example) or use a service like Mailgun for this. This service (like many others) provides its own REST API to send mail but also provides an SMTP relay. So, whatever your mail service is, you can use SMTP to send mail. In Flowlet, this functionality is provided by the “Send mail” block (or with the mail.send function in custom scripts).</p><p>Note that when you use Mailgun, like in this example, you have to use “smtp.eu.mailgun.org” when using the EU instance. Otherwise, it’s “smtp.mailgun.org” as written in their documentation. You can find the username and password in their admin interface.</p><p>The mail block accepts the base64 encoded data as the attachment contents. The mapping doesn’t allow us to create arrays (lists). Hence we have to use the scripted input here. You can access all data from the left side in the “input” object within these fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*9enQ8CvtjCu0fDlfUp1Wog.png" /></figure><p>Note that we didn’t provide the SMTP server directly. Instead, we’ve created a “password” secret in the workspace settings. This secret contains the SMTP connection string, formatted as:</p><pre>smtp://USERNAME:PASSWORD@SERVER</pre><p>Mailgun usernames include an “@” sign, which must be URL encoded. Hence the value looks like:</p><pre>smtp://postmaster%40mg.example.com:PASSWORD@smtp.mailgun.org</pre><h3>Connect services using Flowlet</h3><p>Now that we have discussed all parts — receiving the webhook, rendering the image, and sending mail — we can complete the flow to connect all of them. All actions are executed one after another in this example, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTft1bBpoBirnH4qs_oo8Q.png" /></figure><p>Note that all flows must end at the end block. Otherwise, your webhook will return an error response. After the configuration is completed, we can hit the button in Glide and — if all went well — see the mail arrive with the generated image attached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*8FUlaMpnOp_whRTy5XksBA.png" /></figure><p>And there we have it. The text and image come from the product page in the Glide app.</p><h3>Generating signed URLs for Robolly</h3><p>The URL used for Robolly does not use any authentication (yet you must know the template id). This might not be a concern because the template itself doesn’t likely contain confidential data. However, Robolly provides an option to oblige signatures on each request. The signature is created using a SHA256 HMAC on the string APIKEY:FORMAT:QUERY, for example, xxxxx:jpg:<a href="https://api.robolly.com/templates/63976cb43b1b30621ef96e65/render.jpg?tweet=Lorem+ipsum+dolor+sit+amet%2C+consectetur+adipiscing+elit%2C+sed+do+eiusmod+tempor+incididunt+ut+labore+et+dolore+magna+aliqua.+&amp;name=John+Doe&amp;handle=johndoe">tweet=TEXT&amp;name=NAME&amp;image=URL</a>. Some custom code is required to construct this URL. If we do this, we have to provide the parameters in the URL because the order matters.</p><p>We can use the crypt.hmac function to create the signature, as seen in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*uzMa_KetwkzNGBpW2JUBVw.png" /></figure><p>The request with a signature is not as clean as the request that isn’t signed. The reason is that this kind of authentication is not standardized. The “secret” input (with the secrets section in the settings section) is designed to quickly provide standard authentication schemes, including basic auth and OAuth2. However, we can still get this to work because we can continue in code wherever we are stuck in no code.</p><h3>Wrapping up</h3><p>The Glide app webhook and Robolly rendering make it possible to mail custom images without writing code.</p><p>Can’t wait to connect APIs with Flowlet?</p><ul><li><a href="https://flowlet.app/register">Get started with a 7-day trial</a></li><li>Follow us on <a href="https://medium.com/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=649271db42bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[15 minutes workshop: Create a website uptime monitor in Flowlet]]></title>
            <link>https://medium.com/@Flowlet/15-minutes-workshop-create-a-website-uptime-monitor-in-flowlet-d5d6eab8bcca?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5d6eab8bcca</guid>
            <category><![CDATA[no-code]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[uptime-monitoring]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 13:55:25 GMT</pubDate>
            <atom:updated>2022-12-06T13:55:25.670Z</atom:updated>
            <content:encoded><![CDATA[<p>To act quickly on website downtime, you need to be proactive and create a website uptime monitor. This 15-minute workshop will show you how to create an uptime monitor in Flowlet. It is a quick and educative example of what you can do with Flowlet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19tlPL_j0XonNBT8oo3BOQ.png" /></figure><h4>Why use Flowlet to create an uptime monitor?</h4><p>Flowlet is not a monitoring tool in itself and hence doesn’t ship with all the features you would expect from an uptime monitor. However, with Flowlet, you can add your custom logic and automate various responses. Perform further checks or even reboot your server automatically.</p><h4>What will we build</h4><p>This blog shows a minimal working example of an uptime monitor. You can add multiple URLs that are pinged every 5 minutes. That’s it, but we will give directions for extensions to this system.</p><h4>Collection of monitored websites</h4><p>In your Flowlet workspace, you can access the data collections using the “Data” button in the menu. Use the “Add table” button to create a new collection. Give it the name “Website” and click the “Generate or import” link to generate the structure from the following JSON:</p><pre><br>{<br>  &quot;id&quot;: &quot;FzBg32...&quot;,<br>  &quot;url&quot;: &quot;https://example.com&quot;<br>}<br></pre><p>Then click the “up” label and uncheck the “required” checkbox. When adding new records, we don’t know their status yet. The final schema should match the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*RB89XxrdTozV2ow13-YTdg.png" /></figure><p>Once we have the collection, we will need to add each URL as a separate entry. Click the plus sign (top left of the table) to add a new row. Fill in a URL and hit the checkmark to save the record. To test if the service is working, you may include URLs from services like <a href="https://httpstat.us/">httpstat.us</a> to simulate broken sites.</p><h4>The automated task to update status</h4><p>The next step is to add an automated task that checks each site in the collection for viability. Add a new flow of the “Automated task” type. Then, open the configuration of the start block. Change its name to something meaningful, like “Ping sites”, and set the minute to “every 5 minutes”. Now, you’re all set to build the core of this project; test each site.</p><p>The steps for the fundamental process are as follows:</p><ol><li>Get the list of sites to test.</li><li>Loop through this list.</li><li>Perform an HTTP request. We check the status code that comes back. It should be in the range of 200 to 399. Anything else indicates an error.</li><li>Check if the status is different from the status that is currently stored in our database.</li><li>If the status changes, update the database and send a notification.</li></ol><p>The completed flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pml4Y2wek4s4Cihz8Cv1KA.png" /></figure><p>We’ve used a single if-statement for the fourth step. However, the condition is made up of multiple conditions (status &gt;= 200, status &lt; 400, and not equal to the current stored status). To accomplish this, we can use TypeScript in the mapping dialog, as visible in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*Gayp27XFjlYi__zr4o3ErA.png" /></figure><p>Further down the flow is the “Send notification” flow, which needs some explanation. This block was created as a reusable flow. You can create blocks this way, which is often a convenient method to build isolated parts that you might want to reuse or change later. In this case, we don’t have to touch this automated job when we want to send notifications over another channel. The only relevant detail is the input schema for this block, which you can configure in the start block of the “Send notification” flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*X4lZz3iQ9-uuPHoCvwJ7XA.png" /></figure><p>When you have this flow, you’re already done with the core of our app. It will detect when one of the configured sites goes down! Yet, we’ll likely want some extensions.</p><h4>Sending notifications</h4><p>In our example, we use internal logging to store notifications when a site goes down or up. That is great for testing our uptime monitor, but you likely want to send messages elsewhere.</p><p>You can send notifications by mail using the mail block. For this, you need to bring your SMTP server, which could be a <a href="https://support.google.com/a/answer/176600?hl=nl#gmail-smpt-option">gmail smtp</a> server or a service like <a href="https://www.mailgun.com/">Mailgun</a>. It sounds simple, but mail might take some time to set up correctly due to security concerns and anti-spam measures.</p><p>Another possible target is Slack. They used to have a feature called “Incoming webhooks” that allowed you to do this with ease. However, that feature is deprecated, and you’ll need a full-fledged OAuth2 integration. You can read our blog on <a href="https://medium.com/@Flowlet/handling-custom-slack-commands-with-flowlet-fd8c3b9b9904">creating Slack apps in Flowlet</a>.</p><p>An app that is specialized in sending emergency notifications is PagerDuty. Please read our <a href="https://medium.com/@Flowlet/emergency-response-flow-for-website-downtime-with-flowlet-3eaea5c337a9">blog on Emergency Response Flow</a> for more information on this integration.</p><h4>Adding user accounts and authentication</h4><p>You can combine this application with the <a href="https://medium.com/@Flowlet/how-to-create-your-openid-identity-provider-4623079d9f02">OpenID IdP template</a> to provide user login and authorization. The login is implemented by installing the template and adding the OpenID secret, as you can read in the linked blog. To connect it with the uptime monitor, add a column to the Websites collection named “user”. Use the “id” type and configure it to refer to the User collection (which comes from the OpenID IdP template).</p><p>Some REST API endpoints are needed to allow users to manage their websites. These can use the “openid” secret for authentication. If you do so, the HTTP endpoint flow automatically has the user id available (from the JWT payload), which you can use in the CRUD blocks to list the user’s websites, or link a new website to the user’s account.</p><h4>Get started on your uptime monitor</h4><p>In under 15 minutes, you can create a website uptime monitor in Flowlet. By following the simple steps in this workshop, you’ll be able to keep track of your website’s uptime, so you can take action quickly if there are any issues. Flowlet allows you to extend this concept as you please, whether you want to take automated steps when a site goes down or want to provide this functionality to other users over an API.</p><p>Can’t wait to write APIs with Flowlet?</p><ul><li><a href="https://flowlet.app/register">Get started with a 7-day trial</a></li><li>Follow us on <a href="https://medium.com/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5d6eab8bcca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create your OpenID identity provider]]></title>
            <link>https://medium.com/@Flowlet/how-to-create-your-openid-identity-provider-4623079d9f02?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/4623079d9f02</guid>
            <category><![CDATA[openid]]></category>
            <category><![CDATA[idp]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Wed, 16 Nov 2022 10:10:31 GMT</pubDate>
            <atom:updated>2022-11-16T10:10:31.501Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post will show you how to create your own OpenID identity provider using Flowlet. It is a powerful solution to add secure login to your API for your front-end applications and third parties. The OpenID standard is based on the OAuth2 standard. Therefore, implementing OpenID provides the best compatibility with connecting systems.</p><p>TL;DR: The OpenID IdP described in this post is available as a template in Flowlet. A bare-bones NextJS app that connects to this IdP is <a href="https://github.com/Flowlet/openid-nextjs-base">provided on Github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7o2W3NKNcgAODp4zGLAoLA.png" /></figure><h3>Systems involved in OpenID authentication</h3><p>When a user attempts to log in to a website using OpenID, the following systems are involved in the authentication process:</p><p>The OpenID Identity Provider (IdP): This system stores and manages the user’s OpenID credentials. In most cases, the IdP will be operated by the same organization that runs the website where the user logs in. However, it is also possible for third-party providers to connect to the IdP. This system is sometimes called the authority.</p><p>The Relying Party (RP): This is the website where the user logs in. For an RP to accept OpenID credentials, it must be configured to trust the particular IdP the user is using. You might also see the term Service Provider (SP), which refers to the same systems.</p><p>The User-Agent: This is the web browser. You might not directly regard this system as part of the OpenID framework, but many of the communications involved in the authorization process occur on the client side. It is even possible for the RP to only connect to the IdP from the user agent without their web servers being involved.</p><h3>Requirements to set up your authority</h3><p>Since we’re about to authenticate users, we need a database with user profiles. Each profile must have at least an identifier, a username (could be an e-mail address), and a password. You might also need a scope, depending on <a href="https://medium.com/@Flowlet/oauth2-scopes-for-fine-grained-acls-29efa536f1b0">how you use scopes</a>.</p><p>An OpenID authority needs a login page, consent page, and several API endpoints. The consent page is a page that asks the user’s permission to provide access to a third-party application. Changes are high that you’ve seen a consent page before when logging in with your social media account on another website, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCKi_UyrbtuuOLkUI0w5rw.png" /></figure><p>The most important endpoint is the Discovery endpoint. You can open that endpoint in the browser to find the other endpoints and what features are supported by the IdP. For example, visit the <a href="https://medium.com/accounts.google.com/.well-known/openid-configuration">discovery endpoint for Google accounts</a>.</p><p>Before you add a user login to your app, it is recommended to familisarize yourself with the basics, but you don’t need to know all the details to get started.</p><h3>Login flows</h3><p>OpenID is based on OAuth2 and uses the <em>authorization code grant,</em> <em>implicit</em> grant, and the <em>resource owner password credentials</em> grant. Furthermore, OAuth2 supports the <em>client credentials</em> grant. These flows differ in where the credentials (username/password) are collected and where you want to use the access token. A summary:</p><ul><li>Authorization code grant ⇨ User logs in at the IdP. The access token is known serverside at the RP. The user agent will not retrieve the access token.</li><li>Implicit grant ⇨ User logs in at the IdP. The access token is sent to the user agent. The web server of the RP will not retrieve the access token.</li><li>Resource owner password credentials grant ⇨ User logs in at the RP. The web server of the RP will send the credentials to the IdP and gets the access token. All systems will have access to the credentials.</li><li>Client credentials grant ⇨ does not authenticate a user, but only the RA. The credentials are the client id and client secret.</li></ul><p>For Single Page Apps (SPA), you’ll want to use the implicit grant. Use the authorization code for traditional web apps that are rendered server-side. The credentials grant is the least secure and also the least common.</p><h3>Implementing OpenID login in a Single Page App (SPA)</h3><p>We have published a working OpenID IdP as a Flowlet template, which you can find in the Templates section when logged in to your Flowlet workspace. You can <a href="https://flowlet.app/register">register for a free trial</a> if you do not have a workspace already.</p><p>To use the template, create a new secret (in the settings section) with the name “openid”. This should be an RS256 key pair, as the <a href="https://openid.net/specs/openid-connect-core-1_0.html#rfc.section.7.5">OpenID connect specifications</a> recommended. That is everything you need to set up the IdP. Yet, you’ll need at least one client to use it.</p><p>You can look at our <a href="https://github.com/Flowlet/openid-nextjs-base">example RP app on Github</a>, written in NextJS. The readme file lists all steps required to get this example working. The sample app contains login via OpenID (using the implicit flow) and logout functionality. Use the Flowlet admin to register users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r95nf3tPuXVr8NQqw39_7w.png" /></figure><p>After login, it will fetch the user profile from the user info endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTvuhRCPqdtmIgfxGKrzFg.png" /></figure><p>The provided implementation is a templated intended to quickstart your project. There are several things you might want to change. You’ll likely want to extend the user profile when using this in production. You can do this by adding fields to the User collection in Flowlet. Then edit the GET /api/userinfo flow and open the connection from the Find User block to the HTTP Response. All fields you want to provide to external applications should be connected to the output.</p><p>The OpenID template supports all grant types mentioned above. The first two start with the GET /api/authorize callback. The other two with the POST /api/token flow. That flow is shown below, with annotations to mark the parts that handle the different flows. If you want to disable the password and client credentials flows, you can remove the connection from the first validate block and connect it to the HTTP response block instead, as the green arrow shows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9p9e-dSAYCkIFE0E1yAHWQ.png" /></figure><p>This blog post shows you how to set up your OpenID identity provider using Flowlet. We also created a bare-bones example application that uses this IdP to log in users. The source code is provided to kickstart your project on Flowlet!</p><p>Can’t wait to write APIs with Flowlet?</p><ul><li>Join the <a href="https://flowlet.app/register">waitlist for the private beta</a></li><li>Follow us on <a href="https://medium.com/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4623079d9f02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick & neatly CRUD API]]></title>
            <link>https://medium.com/@Flowlet/quick-neatly-crud-api-9dff0bdfb05f?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dff0bdfb05f</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[low-code]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Tue, 18 Oct 2022 14:03:28 GMT</pubDate>
            <atom:updated>2022-10-18T14:03:28.534Z</atom:updated>
            <content:encoded><![CDATA[<p>Remember hammering the enter button to make your way through installation wizards? Good news;- you can now create your API that way!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49G-jsg1rE3w74B2sNXzDw.png" /></figure><p>In Flowlet, all logic is contained in flows. These work very well for visually defining your logic, but logic isn’t necessarily the first step. When designing an API (whether in a design document or just mentally), it’s more likely that you start with defining the API endpoints. What goes in and what goes out? Precisely that is changed in the latest release. You can now begin with the endpoints and then edit the flows. This feature is just a change in the admin interface without any new functionality or technical changes.</p><p>If we’re building an online chess game, for example, we will have entity types for players and games. Then we can define some API endpoints for this, such as:</p><ul><li>POST /player for user registration</li><li>PATCH /player/123 to set the player’s availability</li><li>GET /player to list the players available</li><li>POST /game to start a new game</li><li>PUT /game/123 to store the result after finishing the game</li></ul><p>The majority of the work is just setting up endpoints for CRUD actions. A little bit of logic remains to ensure that you cannot modify scores later on among some other business rules. As a developer, I like to work on this logic. However, we do not want to spend time on repetitive jobs like developing the CRUD logic.</p><p>We’ve built a new feature in Flowlet to kickstart your API development. You can now set up the rudimentary endpoint with merely more effort than selecting the HTTP method and typing out the path. Completing this wizard results in a new flow built according to our <a href="https://medium.com/@Flowlet/oauth2-scopes-for-fine-grained-acls-29efa536f1b0">best practices for OAuth2 scopes</a> and fully customizable to incorporate your logic.</p><p>You can select an HTTP method and provide a path directly from the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z29c2SW4dMHHnkmjNIw-Mg.png" /></figure><p>We will start with the create operation (what else can we do? — we have no content yet). So, we select the “POST” method and type in “/player”. The next step asks us what this endpoint should do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QrfZDHHNg7FYw_b1Ilp_0A.png" /></figure><p>The last option will create an empty flow, and the script option will add a single script block. Both allow you to define the input and output schemas and will set up the flow accordingly. The first option remains, which we show in this blog.</p><p>You do not provide the crud action. It knows from the HTTP method what is expected. Yet, it still needs to know what to create. A dropdown lists your current data types, with “Player” already selected if you already have it. Otherwise, you choose “Create new collection”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fy0krg9oWh75kTHqvMTtjQ.png" /></figure><p>The next step allows you to define the data schema for this type. It is convenient to generate it from JSON. You can use {&quot;name&quot;:&quot;&quot;} for it. There is also a mandatory “id” property to identify each object, added automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7qdMDXPitoabdvuXA_1bg.png" /></figure><p>Only one step remains. That step is to determine the authentication for this endpoint, for which there are three options; no authentication, API key, or OAuth2. Both API key and OAuth2 will use <a href="https://medium.com/@Flowlet/a-quick-introduction-to-json-web-tokens-jwt-and-jose-95f6e06b7bf7">Json Web Tokens (JWT)</a>. The API key will use an HS256 secret (HMAC) without key rotation. You can create API tokens from the Flowlet admin interface and set the expiration date in the far future. OAuth2 uses RS256 secrets (RSA with public and private key). That is the best option when you want to add login functionality for external users, which we will do for the game API example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjLZ_tyU0nqEyxeporTZ8A.png" /></figure><p>All steps are done. Hit the submit button to create the CRUD flow!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rURmP4wY-y6Q8vskLcir9A.png" /></figure><p>You can then edit the flow or create another endpoint. Let’s first see what we’ve just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8f8pg1Xyb1owyiZjwaiX6w.png" /></figure><p>The flow has a Create Player block that is already connected to the start and end blocks. Furthermore, the endpoint accepts a body and requires authentication. The required scope follows our recommended structure.</p><p>Let’s create the other flows. Add the endpoint to start a game as POST /game using the JSON below for the Game data type.</p><pre>{<br>  &quot;id&quot;: &quot;FzBg32...&quot;,<br>  &quot;black&quot;: &quot;FzBg32...&quot;,<br>  &quot;white&quot;: &quot;FzBg32...&quot;,<br>  &quot;result&quot;: &quot;black&quot;<br>}</pre><p>You can click on the properties for additional settings after creating the schema. Indicate that the black and white properties refer to a Player entity.</p><p>Other CRUD actions (except list) need a path parameter, for example, PATCH /game/123. You use curly brackets for these. Also, its type is automatically set if you give it a name already known as a data type. Therefore, use the path /game/{game}.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SwC8z5M8DGcNgLvvmuHKMw.png" /></figure><p>It will create the flow with the update block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gPUsft2qC0aJ9aMcd2_3w.png" /></figure><p>This flow allows changing the game result multiple times, which is cheating and not what we want. We need to change the flow to incorporate our logic. When adding an “If-statement” block, we’ll see that the game object from the path parameter is already loaded. Therefore, we can directly compare that object’s result to null, the value when empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xi-SFE9H00ni2Gcwdsv2sw.png" /></figure><p>Changing the connections will result in the following flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Wu6OM1MVjql_iBrLcuorw.png" /></figure><p>We’ve seen how you can get a simple crud API up &amp; running with minimal effort while you can still alter and extend its behavior. The API can take advantage of all powerful features like <a href="https://medium.com/@Flowlet/implementation-of-csrf-in-scalable-apis-62f4f3c77606">CSRF-protection</a> and <a href="https://medium.com/@Flowlet/5-cors-headers-your-api-needs-9884a99e50d8">CORS headers</a>.</p><p>Can’t wait to write APIs with Flowlet?</p><ul><li>Join the <a href="https://flowlet.app/register">waitlist for the private beta</a></li><li>Follow us on <a href="https://medium.com/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dff0bdfb05f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of CSRF in scalable APIs]]></title>
            <link>https://medium.com/@Flowlet/implementation-of-csrf-in-scalable-apis-62f4f3c77606?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/62f4f3c77606</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 15:08:55 GMT</pubDate>
            <atom:updated>2022-09-28T15:08:55.298Z</atom:updated>
            <content:encoded><![CDATA[<p>With the rise of cloud-based applications and microservices, it’s more important than ever to have secure and scalable APIs. One common attack vector against APIs is <a href="https://owasp.org/www-community/attacks/csrf">cross-site request forgery</a> (CSRF), allowing an attacker to inject malicious code into a legitimate user’s session. This article will discuss how to implement CSRF protection in a scalable API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ik1k71D8cr5bPQ1QGHr2VA.png" /></figure><h3>What is CSRF in one minute?</h3><p>CSRF, or Cross-Site Request Forgery, is an attack that occurs when a malicious user tricks a victim into submitting a request to a website without their knowledge or consent. That can be done by embedding malicious code in a webpage the victim visits or sending the victim a malicious link via email or social media. Suppose the victim’s browser has an active session with the target website. In that case, the request will be executed with the victim’s credentials, allowing the attacker to perform actions on behalf of the victim.</p><p>An example of a vulnerable request is as follows:</p><pre>POST /api/change-password HTTP/1.0<br>Cookie: sessionId=d35c6ce994e4ea2e20ca5f5101f29105<br>Content-Type: application/x-www-form-urlencoded<br>newPassword=c0rrectH0rseBatteryStaple</pre><p>This request might result from the following HTML form:</p><p>There are a few important elements here. First, the request does something potentially harmful. Second, a cookie is solely used for authentication.</p><p>The attack is simple. The attacker sets up a slightly altered form on evil.com:</p><p>The next step is to trick a victim into visiting the page above. The victim’s password is changed if the victim has a valid session cookie (if logged in). Such events might go unnoticed when the code above is loaded in a visually hidden iframe.</p><h3>Is CSRF an issue for REST APIs?</h3><p>It could be. We mentioned the session cookie for authentication as a crucial element. The point is that the browser will send this authentication, even if the origin (the form on evil.com) doesn’t have it. That is the case for cookies, basic authentication, and IP safelisting.</p><p>The OAuth2 Bearer tokens are not vulnerable to CSRF because the browser will not send them automatically. The front end must provide these tokens explicitly, but the malicious website doesn’t have them. The same applies when you use a custom header for sending API tokens.</p><h3>The Synchronizer Token Pattern</h3><p>The <a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#synchronizer-token-pattern">synchronizer token pattern</a> works by embedding a token in the HTML page that is also stored on the server. The server verifies this token before processing the request, ensuring that the request is legitimate and not part of a CSRF attack.</p><p>We can implement this in the example above by adding a hidden field “csrf_token” to the form. The request then becomes</p><pre>POST /api/change-password HTTP/1.0<br>Cookie: sessionId=d35c6ce994e4ea2e20ca5f5101f29105<br>Content-Type: application/x-www-form-urlencoded<br>newPassword=c0rrectH0rseBatteryStaple&amp;csrf_token=8974f33be5136f71</pre><p>The evil website cannot obtain the token and, therefore, cannot construct a valid form.</p><p>While the synchronizer token pattern effectively prevents CSRF attacks, it can be challenging to implement in scalable APIs. That is because the token must be unique to each user, preferably each request, which we need to store in a database. Exactly the database is the most critical part of scalable apps. Therefore, we would welcome a technique that doesn’t require storage.</p><h3>The Double Submit Cookie Pattern</h3><p>The <a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie">double submit cookie pattern</a> is a method that uses both the browser’s cookie mechanism and a custom header. The idea is to set a cookie with a random value when the user first visits the site. When the user submits a form, that random value is sent in a custom header. The server then checks the cookie and the header values to verify that they match before processing the form submission. So, the server response for the form looks like this:</p><pre>HTTP/1.1 200 OK<br>Content-Type: text/html<br>Set-Cookie: csrf_token=8974f33be5136f71</pre><p>The csrf token is random and is not stored by the server. The request to change the password now looks like this:</p><pre>POST /api/change-password HTTP/1.0<br>Cookie: sessionId=d35c6ce994e4ea2e20ca5f5101f29105; csrf_token=8974f33be5136f71<br>Content-Type: application/x-www-form-urlencoded<br>newPassword=c0rrectH0rseBatteryStaple&amp;csrf_token=8974f33be5136f71</pre><p>The server allows the request if the tokens from the request body and the cookie are identical.</p><p>What if the hacker adds the csrf_token field to the evil form? The hacker can use a random value for this, but it will not match the value in the cookie, or the cookie is missing if the user didn’t visit the page before on the genuine site.</p><h3>Weaknesses of the Double Submit Cookie technique</h3><p>The double submit cookie technique is relatively easy to implement. However, there are a few potential weaknesses with this approach.</p><p>First, the attacker could also use a man-in-the-middle (MITM) attack to set the cookie. That requires additional sophisticated techniques but might still work on sites using TLS (https). The reason is that browsers will first try the non-TLS version if you just type in the domain.</p><p>Second, if the attacker can control a subdomain, it can set a cookie on the top-level domain with a more specific path. That cookie is then also valid for the genuine website.</p><p>Both risks require additional conditions to be exploitable. Nevertheless, these are potential weaknesses to consider when using this approach.</p><h3>Mitigations</h3><p>Web browsers have implemented new security headers and cookie flags to mitigate the described risks.</p><p>The first risk (MITM-attack) requires the victim to visit a website over an unencrypted connection (plain http). The HSTS header prevents this by instructing the browser that the site is only available over TLS. This only works for users that visited the site in the last year (or a shorter period provided in the header). A few new top-level domains (including .app) only support TLS by their standards and offer the same security for new and returning visitors.</p><p>TLS does not mitigate the second risk if the attacker can still control subdomains by other means. Also, setting the domain and other flags at the cookie doesn’t help much, as the attacker can still set his own cookie. This risk is mitigated by setting the cookie value to a cryptographic hash that incorporates secrets only known to the server. The result is that the attacker cannot generate a correct cookie value without knowing the secret.</p><p>Another simple but strong defense is to use a custom header name to send the CSRF token instead of adding it to the body. HTML forms or links cannot implement these custom headers. They must be set by JavaScript, but an external script will result in a cross-origin (CORS) request and is therefore blocked by the browser. An example request with a custom header is:</p><pre>POST /api/change-password HTTP/1.0<br>Cookie: sessionId=d35c6ce994e4ea2e20ca5f5101f29105; csrf_token=8974f33be5136f71<br>Content-Type: application/x-www-form-urlencoded<br>X-CSRF-TOKEN: 8974f33be5136f71<br>newPassword=c0rrectH0rseBatteryStaple</pre><h3>Implementing in APIs</h3><p>To prevent CSRF attacks, developers must implement proper security measures in their web applications. Flowlet allows you to <a href="https://flowlet.app/docs/flows/security-settings">add CSRF protection to any endpoint</a> and implements all mitigations mentioned in this article.</p><p>Can’t wait to write secure APIs with Flowlet?</p><ul><li>Join the <a href="https://flowlet.app/register">waitlist for the private beta</a></li><li>Follow us on <a href="https://medium.com/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62f4f3c77606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Custom Slack Commands with Flowlet]]></title>
            <link>https://medium.com/@Flowlet/handling-custom-slack-commands-with-flowlet-fd8c3b9b9904?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd8c3b9b9904</guid>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[slack-commands]]></category>
            <category><![CDATA[security-token]]></category>
            <category><![CDATA[webhooks]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 09:49:48 GMT</pubDate>
            <atom:updated>2022-09-20T09:49:48.016Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will show you how Flowlet can easily handle custom Slack commands. We will explain the steps needed to set up the Slack app and Slack command, use the OAuth flow to add the app to your workspace and handle calls from Slack in Flowlet to respond to invoked commands. In the last step, we’ll explain how to validate the signatures that Slack sends along the command invocation messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWkusN9s-zOkht6mMQ3Vvw.png" /></figure><h3>What is a Custom Slack Command?</h3><p>A custom Slack command is a slash command that you create yourself. You can use a custom Slack command to do much more, including controlling business workflows or providing a valuable service for Slack users.</p><p>In this blog, we’ll build the “/hello” command. When a user gives in “/hello John” it replies with “Hello John”. This is just a ‘hello world’ example demonstrating the steps required to build more meaningful features.</p><p>Slack sends an HTTP POST request to a pre-set URL when you execute the command. This endpoint can take some action based on the provided command and may directly respond with a message. That is exactly what we’re going to do.</p><p>Several extensions are possible when you have the basic command running. For example, you can add buttons to the message so that Slack users can provide a follow-up action.</p><h3>Set up the Slack App with Custom Slack Command</h3><p>To set up the Slack app, go to their <a href="https://api.slack.com/">developer portal</a> and click the “Your Apps” button on the top-right corner. Then hit the “Create new app” button to get started. You’re asked if you want to use a template or build from scratch. We’ll choose the latter for our use case. You have to provide a name and test workspace.</p><p>Now that your app is created, you can copy over some identification numbers. You must copy some details forth and back from a Flowlet secret, which you can make at the Secrets tab in your Flowlet workspace settings. Copy over the following:</p><ul><li>Fill in the Redirect URL from Flowlet to the Redirect URLs under “OAuth &amp; Permissions” in the configuration of your Slack app.</li><li>In Slack, go to “Basic information” and copy over the Client ID and Client Secret to your Flowlet secret.</li><li>Also, note the “Signing secret” in Slack. We will need this secret later.</li><li>Fill in “https://slack.com/oauth/v2/authorize&quot; as the authorization endpoint and “https://slack.com/api/oauth.v2.access&quot; as the token endpoint.</li><li>Enter “commands” in the scope field. You might add more scopes, but this is the only one required for this tutorial.</li></ul><p>Let’s add this app to your workspace. Click on the “Manage tokens” link On the Flowlet secrets page. The “Request access token” link will lead you to Slack, where you can choose your workspace and authorize the app you’ve just created. Do this now, and you’ll return in Flowlet. You may click the “Manage tokens” links again to verify that you now have an access token.</p><p>That was everything to create an app. However, this app doesn’t do anything yet. It cannot even say hello (world). So, in Slack’s app settings, click on “Slash Commands” (in the sidebar), hit “Create new command” and give in the command “/hello”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*1QJVvP1QENIMW0n7cASiug.png" /></figure><p>The following field — the Request URL — is an important one here. Its value must be an endpoint that you create in Flowlet and thus will be something like https://WORKSPACE.flowlet.app/api/slack-command, where WORKSPACE is the name of your Flowlet workspace. The following step is to set up this endpoint.</p><h3>Handle invocations in a flow</h3><p>We can add an HTTP endpoint flow in Flowlet to handle the command invocations, but we don’t know the expected input and output yet. Before losing ourselves in the docs, configure the flow and see what comes in. The <a href="https://www.youtube.com/watch?v=PxrpL-Ei5N4">marshmallow tower challenge</a> reminds you that the quickest path to a solution is to start testing. To facilitate this, the HTTP endpoint configuration has a checkbox “Save requests to log”. Ensure that the method is set to POST and that the input body can accept all JSON objects. Only requests that pass the initial validation are written to the log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*W4IPsTDXjWgXgOepahutRg.png" /></figure><p>We can already send a command from Slack and check the Flowlet logs to see what’s coming in. Use that information to generate the input schema for the HTTP endpoint, so you’ll end up with the configuration seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*OoMPP0t-kN74RRn8R8AleQ.png" /></figure><p>Next, we need to know what Slack expects from the endpoint. You can find a <a href="https://api.slack.com/interactivity/slash-commands#responding_immediate_response">simple example in the Slack docs</a>. Now configure the end block and generate the schema from that example. If all goes well, you can short-circuit the start with the end block and provide a response like the one below.</p><pre>[<br>  {<br>    type: &quot;section&quot;,<br>    text: {<br>      type: &quot;mrkdwn&quot;,<br>      text: &quot;Hello &quot; + input.requestBody.text,<br>    },<br>  },<br>]</pre><p>If all went well, your mapping looks like this.</p><p>Going back to the Slack application, I can type “/hello Maurits” and get back the response “Hello Maurits” as I would expect from the code above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*sUuZJu5u1_a4GYPvc4Uz_A.png" /></figure><h3>Verifying the Webhook Signature</h3><p>The custom Slack command already works, but there is one issue. Everybody can send a POST request to your endpoint. How can you check that these calls are valid?</p><p>To verify that the request comes from Slack, you must compute the signature and compare it to the one included in the request header. If they match, you know that the request is genuine and can process it accordingly.</p><p>Look at the Flowlet logs and find the signature in the HTTP request headers. You’ll see the x-slack-request-timestamp and x-slack-signature headers. Furthermore, remember that you got a Signing Secret earlier. Slack uses this secret to calculate the HMAC-SHA256 from the “v0:TIMESTAMP:BODY” input string. Here, TIMESTAMP is replaced with the value from the timestamp header, and BODY must be the raw JSON body received from Slack. This is a common strategy for validating webhooks, and for that reason, Flowlet provides a requestBodyRaw input property.</p><p>Connect the start block with a new “If-statement” block to validate the signature in your flow. For the “a” input, we’ll use a code field with the code below.</p><pre>crypt.compare(<br>  crypt.hmac(<br>    &quot;v0:&quot; +<br>      input.inputHeaders[&quot;x-slack-request-timestamp&quot;] +<br>      &quot;:&quot; +<br>      input.requestBodyRaw,<br>    &quot;a0ae88b7f4a03d81f024a26bfcd4b960&quot;,<br>    &quot;sha256&quot;<br>  ),<br>  String(input.inputHeaders[&quot;x-slack-signature&quot;]).substring(3)<br>)</pre><p>Flowlet provides the HMAC-SHA256 signature via the crypt.hmac function, as seen above. This method returns the signature as a hexadecimal string that has to match the X-Slack-Signature header. However, the value of that header has the format “v0=SIGNATURE”. We’ll use a quick &amp; dirty way of stripping that prefix for now.</p><p>Instead of crypt.compare, we might just compare the strings with JavaScript’s equal operator. However, this leaves your application vulnerable to <a href="https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#compare-password-hashes-using-safe-functions">timing attacks</a>, so we should use crypt.compare for comparing security tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*8E2AeD-msc6OImUmKiPAxg.png" /></figure><p>To finish the configuration for the “If-statement” block, connect the “b” input to a code field and enter “true”. You can continue the flow from the “then” pin while connecting the “else” pin directly to the error output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*vg86xGx9nCHQysSkAEfxkw.png" /></figure><h3>Conclusion</h3><p>This article shows you how to use Flowlet to get started building custom Slack commands. We used code for the complex parts and to format the custom response, which is hardly more complicated than just JSON. Low code enables you to configure most of the application while keeping the flexibility to create meaningful integrations.</p><p>Want to build your API integration using Flowlet?</p><ul><li>Join the <a href="https://flowlet.app/register">waitlist for the private beta</a></li><li>Follow us on <a href="https://medium.com/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd8c3b9b9904" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No-code your Hubspot API calls]]></title>
            <link>https://medium.com/@Flowlet/no-code-your-hubspot-api-calls-914eca4d7f63?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/914eca4d7f63</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[no-code]]></category>
            <category><![CDATA[hubspot]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 08:09:38 GMT</pubDate>
            <atom:updated>2022-09-13T08:09:38.438Z</atom:updated>
            <content:encoded><![CDATA[<p>Hubspot is a powerful marketing and sales CRM, and their API lets you access data stored in their systems so that you can use it in your apps and integrations. In this article, we’ll show you how to make Hubspot API calls using Flowlet without the need to code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pyprEpH9quJnH0Fen10-A.png" /></figure><h3>Obtaining Hubspot API keys</h3><p>To make Hubspot API calls, you need a token to authenticate your requests. That used to be an API key, but you’ll find that Hubspot has superseded API keys with something called “Private apps”. Each private app gives you a token that, in fact, is an API key. The difference is that Hubspot private apps let you create a token per application and narrow the scope for each. That improves the security of your account by following the <a href="https://medium.com/Principle%20of%20least%20privilege">principle of least privilege</a>.</p><p>To create a private app, click the cog on the top-right corner of your Hubspot account, click “Integrations”, and then “Private apps” in the sidebar.</p><p>When creating an app, you must provide a name and the scopes. The scopes determine which resources the newly created token has access to. In this blog post, we’ll create a contact entity as an example and hence need the “write” permission for contacts. You may want to add more scopes for further experimentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Nub1YF4L2PEsuGYugAK44g.png" /></figure><p>Copy the token that you get directly after creating your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*zr64gDM7t7KUq1kgybcSgg.png" /></figure><p>Then, go to “secrets” under your Flowlet workspace’s settings. Create a new secret of the “password” type. Give it the name “hubspot” and set the token as the password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*OMyoiKJMOREy9CPBc5UJHA.png" /></figure><p>There are more types of secrets in Flowlet. You can use three of them for authorizing API requests. Besides “password”, these are “basic authorization” and OAuth2. The latter is used for public apps connected to multiple accounts.</p><h3>Creating a flow to test</h3><p>We want to trigger the API call somehow. For example, create an HTTP endpoint flow, set the method to POST, and generate the post body from the following JSON code:</p><pre>{<br>  &quot;company&quot;: &quot;Biglytics&quot;,<br>  &quot;email&quot;: &quot;<a href="/service/mailto:bcooper@biglytics.net">bcooper@biglytics.net</a>&quot;,<br>  &quot;firstname&quot;: &quot;Bryan&quot;,<br>  &quot;lastname&quot;: &quot;Cooper&quot;,<br>  &quot;phone&quot;: &quot;(877) 929-0687&quot;,<br>  &quot;website&quot;: &quot;biglytics.net&quot;<br>}</pre><p>To make an HTTP request, drag the “request” pin from the start block to an empty space. The “Add block” dialog appears when we select the “HTTP request” block. The mapping dialog pops up. Before we know what to fill in, we’ll look at Hubspot’s API docs.</p><h3>Exploring the Hubspot developer docs</h3><p>You’ll find that most services you want to connect with have a separate developer portal, such as <a href="https://developers.hubspot.com/">Hubspot developers</a>. Within this portal, you’ll find the API reference that lists all available calls. In this case, we are interested in the <a href="https://developers.hubspot.com/docs/api/crm/contacts">Contacts API</a>. Click on the “Endpoints” tab and select the “Create” call in the dropdown. That brings you to the documentation on creating a contact using the Hubspot API. You can see that we took the JSON example above from this page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*5xC8UsIiWoUr2i8gOVrrmQ.png" /></figure><p>According to the docs, the scope crm.objects.contacts.write is required for this call. The Private App’s configuration did not mention this exact name, but it’s just the “write contacts” permission listed there.</p><p>In the command line example (using curl), you’ll see that the method is POST, and the URL is https://api.hubapi.com/crm/v3/objects/contacts. Furthermore, they provide the header Authorization: Bearer YOUR_ACCESS_TOKEN.</p><h3>Making Hubspot API calls in Flowlet</h3><p>We ended the test flow at the mapping dialog. If you closed it, you may re-open it by clicking the hourglass icon at the line to the HTTP request block.</p><p>You can easily set the HTTP method and URL in Flowlet. Also, provide the authorization by selecting the “secret” input with the secret you’ve created. That will add the Authorization: Bearer TOKEN header seen in the docs, where the actual value of the secret replaces TOKEN. For this, you can drag the secret pin to an empty field on the left. You’ll see that the field changes to a dropdown that lets you select the correct secret.</p><p>The last thing to configure is the post body. Hubspot expects an object with the “properties” property that holds all our data. You can construct such objects from the mapping dialog. For example, drag the “company” item on the left to “body” on the right. You are asked how you want to map this data. This is the crucial step in constructing new objects. Select the second property and type in “properties/company”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*e-Vulydi4f3koMlJoz3w6w.png" /></figure><p>You can see an example of the completed mapping in the following screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*c9qsXtI-mBxTbtTBadarmA.png" /></figure><h3>Testing the API call</h3><p>In Flowlet, click the “Test flow” button on the top-right corner. Scroll down in the input field and fill in some sane details to post to Hubspot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*pdkem2EeGLa4TGsBuAYzpQ.png" /></figure><p>The blocks that ran successfully get a green shadow after clicking the “Run flow” button. A new icon appears that lets you inspect its in- and output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*Dlt1TrxnE1PyJT67162IMQ.png" /></figure><p>You’ll see the response from Hubspot in the output, with the ID of the contact entity just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*NSiOU-49tm22h242ZWEsgg.png" /></figure><p>We can also check the entity in Hubspot itself, where we see the new item on the contacts page.</p><h3>Conclusion</h3><p>With just a few clicks, you can easily connect your HubSpot account to Flowlet and add custom logic. Creating contacts is just one example. You can create and edit all your Hubspot data with their API. You can use low-code flexibility to enrich your Hubspot data or automate marketing tasks.</p><p>Want to build your API integration using Flowlet?</p><ul><li>Join the <a href="https://flowlet.app/register">waitlist for the private beta</a></li><li>Follow us on <a href="https://medium.com/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=914eca4d7f63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Update entries with the Contentful API]]></title>
            <link>https://medium.com/@Flowlet/update-entries-with-the-contentful-api-7e22e75d1702?source=rss-647fcad7514------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e22e75d1702</guid>
            <category><![CDATA[updates]]></category>
            <category><![CDATA[entry]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[contentful]]></category>
            <dc:creator><![CDATA[Flowlet]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 08:11:08 GMT</pubDate>
            <atom:updated>2022-09-06T08:11:08.524Z</atom:updated>
            <content:encoded><![CDATA[<p>Contentful is a powerful headless CMS that can help you manage your content easily. This week’s article is a hands-on guide that shows you how to amend the content in Contentful using their API and webhooks. We’ll use a content type “Blog” with a rich text body and a field “word count” that we will update automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJNBJm6AknpJ3d8nZUsGPw.png" /></figure><h3>Different Contentful APIs</h3><p>When you look at the <a href="https://www.contentful.com/developers/docs/references/">Contentful developer docs</a>, you’ll find multiple APIs. The <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/">Delivery API</a>, which you can only use to retrieve published content, is targeted at building websites. You need the <a href="https://www.contentful.com/developers/docs/references/content-management-api/">Management API</a> to create or update content.</p><p>An API key is required to make requests to the Management API. These can be created in Contentful under Settings &gt; API Keys. Click the “Generate personal token” button under the “Content management tokens” tab. In the Flowlet settings, create a new secret of the “password” type. Give it the name “contentful” and use the token from Contentful as the password.</p><h3>Setting up the webhook</h3><p>In this example, we will update a field after changing an entry. We can use webhooks to trigger the flow in Flowlet. Under Settings &gt; Webhooks (in Contentful), create a new webhook and set the URL to:</p><pre><a href="https://workspace.flowlet.app/api/contentful-webhook">https://WORKSPACE.flowlet.app/api/contentful-webhook</a></pre><p>Where WORKSPACE is the name of your Flowlet workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wSKDA3sBbEHg6eeIdY6MQ.png" /></figure><p>Most webhooks applications will send a signature that you can use to verify that incoming requests are valid. Contentful does not send a signature. Instead, we can set credentials that they will send to our webhook. Click the “Add Basic auth header” link and set a random username and password. Also, create a secret of the “Basic auth” type in Flowlet where you configure the same credentials.</p><p>You might enable the webhook for all events, but it creates a lot of noise while testing. It’s best to start with a single action only to avoid confusion while testing. In our case, only tick the “publish” action for the blog post. In our use case, there is another crucial reason not to include all operations. We will update the content from our webhook itself. Hence we must ensure that a webhook does not trigger another webhook, and thus an infinite loop of updates.</p><p>Lastly, we need to create the HTTP endpoint on the path mentioned above in our Flowlet workspace. In its settings, uncheck “Open access” and check the basic auth we’ve created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUJ6zjDQijldpL-NjBH5SQ.png" /></figure><h3>Updating Entries with the Management API</h3><p>Contentful uses <a href="https://en.wikipedia.org/wiki/Optimistic_concurrency_control">optimistic locking</a> when updating content. In short, it means that you must provide the current version number when updating content, even if you’re sure that concurrent updates will not happen. Therefore, to update an entry, you first need to retrieve it from Contentful. This request requires a few identification numbers that we get in the post body. We can use them directly in the mapping dialog’s code field to construct the API endpoint as follows:</p><pre>`<a href="https://api.contentful.com/spaces/$%7B">https://api.contentful.com/spaces/${</a><br>  input.requestBody.sys.space.sys.id<br>}/environments/${<br>  input.requestBody.sys.environment.sys.id<br>}/entries/${<br>  input.requestBody.sys.id<br>}`</pre><p>Furthermore, connect the “secret” input for the HTTP request to a code field. A dropdown will appear that lets you select the secret created earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pu9ZgamtLFUV-KcZ7zrlig.png" /></figure><p>We must validate the output of the request before you can use it in the flow. Because the response format depends on the fields you’ve defined in Contentful, you should use the request output to generate the validation schema. Open the configuration of the start block and check “Save requests to log”.</p><p>Update and publish a blog entry in Contentful and return to Flowlet. Click on the “Test flow” button on the top-right of the flow page and then click the “view logged request” link (this only appears when the save to log option is enabled). You should now see the last request made by Contentful. Click on it to see details, and click on the “Test flow” button to go back to the flow. This prefills the input data in the sidebar with the actual data from the Contentful webhook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iiQDDtFQZ9tVQ4maa2QhA.png" /></figure><p>New buttons appear on the blocks after running the flow. These let you inspect the input and output data of these specific blocks. Click on this icon at the request block. You should now copy the JSON data of the body property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXHdaqqgAPy3eR2PEhDiyg.png" /></figure><p>Proceed with creating a validate block after the request block. Choose “Edit schema” in its settings and click on “generate or import”. You can now use the copied JSON value to generate the validation schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6sMok7O3gUzCUPizyYsrQ.png" /></figure><p>The last step is to add another request to update the content. The Contentful Management API has two options for updating an entry; you can use the PUT method and send the whole (updated) entry in the request or use the PATCH method and send a body in the <a href="https://jsonpatch.com/">JSON patch format</a>. You may directly code the patch in the input for the request block. In our example, we’ve used the code below:</p><pre>[<br>  {<br>    op: &quot;add&quot;,<br>    path: &quot;/fields/wordcount&quot;,<br>    value: {<br>      &quot;en-US&quot;: input.requestBody.fields.body[&quot;en-US&quot;].content.reduce(<br>        (count, item) =&gt;<br>          count +<br>          item.content.reduce(<br>            (count, item) =&gt; count + item.value.split(/[\s]/).length,<br>            0<br>          ), 0<br>      )<br>    }<br>  }<br>]</pre><p>Also, set the Content-Type header to application/json-patch+json, provide the current entry version in the X-Contentful-Version header, and add the API key to the secret input. You can retrieve the version with the code input.body.sys.version.toString().</p><p>You can rerun the flow from Flowlet to update the entry. If that works, you can edit and publish an entry in Contentful. Then refresh the page and check if the word count was updated accordingly.</p><h3>Conclusion</h3><p>All APIs have their own peculiarities. In Contentful, you must handle the optimistic locking, a concept many developers might not have seen before. You need to add this to the HTTP request headers. Furthermore, the content type differs from the typical “application/json” type, and we need to secure our webhook with authentication. Flowlet handles these requirements without the need to write custom code. In fact, we’ve only used coding to construct the URL (a simple string literal) and create the patch, which is at the core of what we’ve achieved.</p><p>Want to build your microservice using Flowlet?</p><ul><li>Join the <a href="https://flowlet.app/register">waitlist for the private beta</a></li><li>Follow us on <a href="https://medium.com/@Flowlet">Medium</a>, <a href="https://twitter.com/flowletapp">Twitter</a>, or <a href="https://www.linkedin.com/company/flowlet/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e22e75d1702" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>