<?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[The RESTful Web - Medium]]></title>
        <description><![CDATA[Curated Thoughts on HTTP, REST &amp; Hypermedia APIs - Medium]]></description>
        <link>https://medium.com/the-restful-web?source=rss----b0d9bf327991---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>The RESTful Web - Medium</title>
            <link>https://medium.com/the-restful-web?source=rss----b0d9bf327991---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 15:29:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/the-restful-web" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Lessons learned from building the best API marketplace in the world]]></title>
            <link>https://medium.com/the-restful-web/lessons-learned-from-building-the-best-api-marketplace-in-the-world-a4c1c1d8bb84?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/a4c1c1d8bb84</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[online-marketplace]]></category>
            <category><![CDATA[marketplace-software]]></category>
            <dc:creator><![CDATA[orliesaurus]]></dc:creator>
            <pubDate>Mon, 21 May 2018 14:41:17 GMT</pubDate>
            <atom:updated>2019-11-06T21:56:23.505Z</atom:updated>
            <content:encoded><![CDATA[<p>A while back I worked for an <strong>amazing</strong> <a href="https://en.wikipedia.org/wiki/Mashape">company</a> known for having the largest API marketplace on earth! I’ve learned how hard it can be to grow a marketplace business and be successful! Acquiring users is tough, especially when they’re <strong>developers</strong>!<br>Creating a great playground for API developers to<em> find, consume and publish APIs </em><strong>isn’t a simple feat<em>. </em></strong>It requires a really strong and dedicated team, focused on developer experience.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fz6iMMxpd3Id7G%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fz6iMMxpd3Id7G%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fz6iMMxpd3Id7G%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/f28e01d307791de5a8449f944d3548a1/href">https://medium.com/media/f28e01d307791de5a8449f944d3548a1/href</a></iframe><p>This blog post is based on personal experiences, learned through lots of life lessons &amp; hard work! If you want to hear specifics on a certain aspect of the marketplace, <a href="https://www.twitter.com/sunglassesface">feel free to reach out to me on Twitter</a></p><h4>Initially…</h4><p>When I joined the company the objective had been to <strong>scale </strong>the API marketplace to infinity and beyond (!!). To become the largest single hub for API developers.</p><p>A lot of challenges and successful moments later, today the company works on the world’s most popular open source API gateway. Built <strong>in the open</strong> on <a href="https://github.com/Kong/kong/commits/master?after=89394c9cf31dae1494f2ebb01c378f91c0595364+3485">Github</a> as a developer-first product. They did really good in the microservice enterprise scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AM1wR3dpFp-Q-dLIS_8cQ.png" /><figcaption>Source: konghq.com</figcaption></figure><h3>Working Marketplace Magic In A Developer-First Market</h3><p>Hold on! What’s an API marketplace? What’s a marketplace business model? <strong><br></strong>In a marketplace you have:</p><ul><li>people selling some kind of goods (or services)</li><li>people looking for these goods (or services)</li></ul><p>As the provider of the marketplace you need to make sure sellers and buyers respect the rules of the marketplace and are satisfied with all aspect of the transactional experience.</p><p>These two groups need to be <strong>mutually interested</strong> in each other for the marketplace to thrive.</p><p>You, as in the entity who runs the marketplace, are trying to provide the best possible experience to both sides. The most old-school example of a two sided marketplace is <strong>eBay</strong>.<br>The more traditional marketplaces are:</p><ul><li>Amazon, Etsy, AliBaba</li></ul><p>and some companies that deal directly in the b2c space, like:</p><ul><li>Uber</li><li>Lyft</li><li>Tinder</li><li>Doordash</li><li>Postmates</li></ul><p>and many other..</p><h3>A little background on how the API marketplace was born…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8jN0el-4h0knlczPjK90Q.png" /><figcaption>REST APIs interest over time, courtesy of Google Trends</figcaption></figure><p>Around <strong>2010</strong> everyone started <strong>dreaming</strong> about connecting Apps with APIs.<br>The web had just stopped talking about widgets, mashups, HTML5 was at this stage *hot*, APIs were definitely the new cool thing.</p><p>Around <strong>2011</strong> the initial concept of an API marketplace was born. Initially as a mere index of public APIs — developers could push their API to the platform and provide documentation for others, “API consumers”, to learn and use it.</p><h4>The early days</h4><p>In the first iteration of the API marketplace, all you could do was track the amount of developers using an API, think of like <em>ProductHunt for APIs </em>😸<em> </em>— a list of people who would up-vote an API as they made request to it.</p><p>The more developers using an API, the highest the popularity of that API on the global marketplace index.</p><p>At this stage the marketplace’s sole service was authentication. You would make a request through the marketplace server with your API-key, you would get a token and then you could use this one-time <strong><em>(!!!)</em></strong> valid token to request any of the API’s hosted (or rather proxied) by the Marketplace. What a mess!</p><h4>Golden API Adoption Days</h4><p>Then suddenly around <strong>2013–2014</strong> <strong>everyone, </strong>literally<strong>, </strong>jumped on the API wagon, just as predicted. Hackathons were huge, people were living off pizza and beer and API meetups and conferences started popping up!</p><p>On Mashape things had to scale up on all fronts, as API usage would become more popular, and API requests too. Re-writing the marketplace and making everything work better was the core priority of the team.</p><p><strong>Relaunching and completely rewriting the marketplace was a huge feat. </strong>The platform was reshipped as Mashape 5 with an improved design, a better user experience and more services for the end-users.<br>This came at a price, the engineering team spent countless nights sleepless after the launch to ensure a smooth transition.</p><p>Scaling the marketplace throughout the years took a <strong>HUGE</strong> amount of work. Luckily our team was young, full of passion and very energetic!<br>There were monitors held around the office focused on the KPIs. We noticed people were looking at the monitors when walking in but weren’t stopping by them as much as we would have liked it. <br>We then decided to send daily reports via email which we would discuss during our stand up meetings.</p><p>Looking at where users would get stuck and the feedback coming in through our customer support account had helped us immensely <strong>re-shape </strong>some rough edges of the marketplace diamond.</p><p>Changing/adding features that were requested by customers had to be prioritized (using a huge Trello board) properly. We had so much stuff we wanted to do. It quickly became our obsession.</p><p>We also focused on creating a lot of documentation, videos and FAQs for on-boarding.</p><p>This tough time have ultimately shaped the company — picking up pace, switching gears and moving into a leading microservices-first enterprise software position.</p><h3>Scaling up the marketplace operations</h3><p>Scaling up the marketplace required a lot of work: platform features, developer outreach, clever “startup-py hacks”, open source contribution and sweating. By the end of 2012 the platform only hosted around a thousand public APIs.</p><h4>Meanwhile…</h4><p>While other platforms like <strong>ProgrammableWeb </strong>were focusing on the indexing issue — this marketplace was focusing <strong>on adding useful services</strong> that would allow service providers to benefit from having their API on the Marketplace.</p><blockquote>The idea was simple: <br><strong>Create value for providers (sellers), the harder demographic to onboard and the consumers (buyers) will come.</strong></blockquote><p>As an API provider you needed things like:</p><ul><li>Caching</li><li>Throttling</li><li>Authentication</li><li>Customer support</li><li>Analytics</li><li>Documentation</li></ul><p>These tools would ensure your API would become useful to developers world-wide, but at the same time you had to focus on the quality of the results returned by your API.</p><blockquote>API service providers learned the hard way that being developer-centric would set them aside from competitors and give them a bigger chunk of the market.</blockquote><p>By providing these layers of services to API providers it meant that developers could spend more time writing good code and good documentation!</p><p>Throughout the years of 2013, 2014 and 2015 the marketplace reached critical mass, there were over 10000 APIs a large part of which were private and used by small businesses (digital agencies, small dev shops etc) that would sell access to their home-grown API to select third parties.</p><p>The benefit of using the <strong>Marketplace</strong> was that all the extra services were free, they would come out of the box — as a consumer you’d have the fastest way to find, use and implement APIs. As a provider you we were holding your hand to launch your API.</p><h3>Dawn to Dusk In The Marketplace</h3><p>After 2010… APIs exploded. That’s also what changed the marketplace.</p><p>APIs were driving businesses from garage startups to IPO-bound — <strong>Twilio </strong>had started just 2 years prior — similar companies as them, pioneers of API-driven businesses were pretty huge, already reached millions of dollars of annual revenue. SendGrid was another one.</p><blockquote>These kind of businesses were getting huge and were never going to move to the Marketplace model.</blockquote><h3>⚡ Dissecting what could‘ve been done differently</h3><p>Most if not all marketplaces follow this path of growth:</p><ul><li>They expand into new markets and locations</li><li>They start to add new features, products for buyers and sellers</li><li>They make it super simple to buy and sell API</li><li>They grow and scale both on the supply and demand side</li></ul><p>The API marketplace managed to do a lot of this, yet, not enough of it.</p><h4>#1. Never Fail. Provide Options Instead.</h4><p><strong>Realize you are the biggest point of failure of someone’s stack.</strong><br>Just like AWS/Cloudflare/Google, when their services go down everyone suffers. When the main API proxy went down, every single API would also suffer. In our world when your infrastructure powers thousands of applications and their customers (free and paid) getting even 10 minutes of downtime means everyone and their cousins will suffer. As a silly example think of weather APIs, traffic APIs, mapping APIs hosted on the marketplace powering mobile apps and more going down — think of the effect a little downtime produced on all the apps that rely on these.</p><h4>#2. Trust and SLAs — Business Criticality</h4><p><strong>Businesses don’t mess around</strong>.<br>Big API consumers are large businesses. They have both internal and external APIs and as they scale, you scale.<br>The earlier reason, a marketplace being the biggest possible point of failure, means that you need to have a resilient API proxy. When your customer is a big enterprise you will have to guarantee a certain level of service. The best way to do that is to have the proxy deployed as close as your customer’s heart as possible. This was however not what the marketplace was all about.</p><p>Years later it became apparent that something had to change and centralizing things wasn’t going to work for everyone. Therefore with the creation of Kong this vision became more and more clear and eventually took over.</p><h4>#3. Monetize Fast, Monetize A Large Demographic &amp; Monetize’em Good</h4><p>As an API marketplace owner you need to monetize all the services that you provide. There are many revenue models you can go after but the best one is providing a set of tools to the users of the marketplace and charging <strong>them</strong> a premium for access.<br>In the API marketplace a lot of the service were built and <strong>offered for free</strong> while they could’ve been monetized into chunks. Analytics, documentation, etc.<br>At the same time because of the way the API marketplace was built and because of problems #1 and #2, developers would never be able to trust a platform that handled billions of API calls. The demographic the marketplace was going after was too niche — small and medium groups of developers.</p><h4><strong>#4. Maintain &amp; Update A Lot Of Community Code</strong></h4><p>Part of what made Mashape successful was the ability to consume API using own wrappers and libraries. This made consuming simple: A lot of copy paste and a few terminal commands and you would be consuming API like a boss. This clever trick alongside with the explosion in adoption of open-source libraries such as <a href="https://github.com/Kong/unirest-java">Unirest</a>, available for most programming languages, made it so that anyone with little effort could consume an API from the marketplace. However as things grew and got out of control it became increasingly hard to maintain all the Unirest libraries, this is apparent by just visiting the “issues” section on Github that keep accumulating.</p><h3>The future for API marketplaces</h3><p>Today, there are a lot of new marketplaces that are developer focused.</p><p>Personally, I don’t think developer centric API marketplaces will take off <em>among developers</em>.</p><p>I love the idea that Zapier has built. The vision <strong>#3</strong> (monetize the largest demographic — people who want to get sh!t done) and <strong>#4 </strong>(tools to scale) perfectly, while they’re probably still working hard on <strong>#1</strong> and <strong>#2.</strong></p><p>They truly delivered on the vision of 2-sided marketplace, not only developers (providers and consumers) but also non-developers!</p><p>That is:<br><strong>Monetizing a platform that allows non-developers to use APIs (n.b. without technical expertise) in the tools they use every day. Monetizing API providers by allowing them to enter the marketplace to reach these non-developers.</strong></p><p><strong>Zapier</strong> has a lot of competitors such as <em>StamPlay</em> and <em>Tray</em>.io, clearly so they must be doing something right — especially across organizations that are pretty large and need to empower their marketing, operations and other teams that don’t necessarily write code.</p><p>In my opinion the reason the original API marketplace is no more, is a direct evolution of the demand of its own users. That is — with the creation of a open-sourced self-hosted software for developers there’s no need to centralize anything anymore. This allows any developer (or team of)to manage their own API <strong>on their own terms</strong>. As opposed to a big closed-source platform, you give the power back to the people!</p><p>It turns out it’s a winning strategy and as time has shown — API gateways are now a common thing.</p><p>Next time you start thinking to build a marketplace for developers, make sure you evaluate very carefully your business model — think far and further!</p><p>I love marketplaces. The concept is intriguing. I’ve spent the last couple of years working on 2-sided marketplace businesses. Heck I’m working on a marketplace business right now.</p><h4>👉 Before you go: <a href="https://www.twitter.com/sunglassesface">Connect with me on Twitter</a></h4><p>Thanks for reading this far I had to dig through notes and memories — Now, if you made it this far you might as well just leave an emoji-reply or a text-reply below 👇! Or Clap 👏?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4c1c1d8bb84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/lessons-learned-from-building-the-best-api-marketplace-in-the-world-a4c1c1d8bb84">Lessons learned from building the best API marketplace in the world</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Daily Mix” with Postman Monitors and Spotify]]></title>
            <link>https://medium.com/the-restful-web/daily-mix-with-postman-monitors-and-spotify-3a020185ffec?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/3a020185ffec</guid>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Ankit Sobti]]></dc:creator>
            <pubDate>Wed, 29 Mar 2017 15:28:09 GMT</pubDate>
            <atom:updated>2017-03-29T15:28:08.729Z</atom:updated>
            <content:encoded><![CDATA[<p>This continues from my previous post, <a href="http://blog.getpostman.com/2016/11/09/generate-spotify-playlists-using-a-postman-collection/">Music Discovery with Spotify and Postman</a> and concludes the series <a href="http://blog.getpostman.com/2016/03/23/conditional-workflows-in-postman/">Conditional Workflows in Postman</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypijdzmFs4YsZvQv_ZHhlw.png" /></figure><p>We last learnt how to make a collection that generates a playlist with music from your favorite artists using the Spotify API. We then ran the collection in the <a href="http://getpostman.com/apps">Postman App</a> and <a href="https://www.npmjs.org/package/newman">Newman</a>.</p><p>Today, we’re going to take this one step forward and emulate 2 awesome Spotify features for music discovery — <a href="https://www.spotify.com/int/discoverweekly/">Discover Weekly</a> and <a href="https://news.spotify.com/us/2016/09/27/rediscover-your-favorite-music-with-daily-mix/">Daily Mix</a>. And we’ll use 2 new features in the <a href="https://blog.getpostman.com/2016/12/15/introducing-postman-pro/">Postman Pro</a> arsenal to do this — <a href="https://monitor.getpostman.com/">Postman Monitors</a> and the <a href="https://api.getpostman.com/">Postman Pro API</a>.</p><p><a href="https://monitor.getpostman.com/">Postman Monitors</a>, launched in January 2017, lets you check for the performance, uptime and correctness of your API. It’s built on <a href="https://www.getpostman.com/docs/collections">Postman Collections</a> running on the cloud on a specified schedule.</p><p>The <a href="https://api.getpostman.com/">Postman Pro API</a> exposes several endpoints to help you integrate Postman more deeply with your development toolchain. Using the API, you can create and update collections and environments, and run monitors, simultaneously syncing each action with your Postman app. All new features (e.g. <a href="https://blog.getpostman.com/2017/03/16/simulate-a-back-end-with-postmans-mock-service/">Postman Mock Service</a>) will be launched first via the API before making their way into the app.</p><p>As you would have guessed by now, we’ll use Postman Monitors to run our simple yet effective music discovery collections once a day (or week) on the cloud.</p><p>Quickly jotting down the workflow:</p><p>1. Add a new request to our collection which <a href="https://api.getpostman.com/#e0d6-3bc3-3da5-ab57-7a578a8504ce">updates the environment</a> at the end of the run using the Postman Pro API. This allows us to emulate the Persist Variables feature in the app.<br>2. Create a monitor with the updated collection and environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E91Sxq9KMjPRKyqFNEILLA.png" /><figcaption>This is what the updated workflow looks like</figcaption></figure><p>You can check out the documentation for the collection <a href="https://documenter.getpostman.com/view/583/spotify-playlist-generator-v2/2Mssx3">here</a> and download the collection <a href="https://app.getpostman.com/run-collection/6f54f4707924fc930d6e#?env%5BSpotifyGenV1.template%5D=W3siZW5hYmxlZCI6dHJ1ZSwia2V5IjoiYXJ0aXN0cyIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifSx7ImVuYWJsZWQiOnRydWUsImtleSI6Ik4iLCJ2YWx1ZSI6IjUiLCJ0eXBlIjoidGV4dCJ9LHsiZW5hYmxlZCI6dHJ1ZSwia2V5IjoidXNlcl9pZCIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifSx7ImVuYWJsZWQiOnRydWUsImtleSI6ImNvdW50cnlfY29kZSIsInZhbHVlIjoiVVMiLCJ0eXBlIjoidGV4dCJ9LHsiZW5hYmxlZCI6dHJ1ZSwia2V5IjoiY2xpZW50X2lkIiwidmFsdWUiOiIiLCJ0eXBlIjoidGV4dCJ9LHsiZW5hYmxlZCI6dHJ1ZSwia2V5IjoiY2xpZW50X3NlY3JldCIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifSx7ImVuYWJsZWQiOnRydWUsImtleSI6InJlZnJlc2hfdG9rZW4iLCJ2YWx1ZSI6IiIsInR5cGUiOiJ0ZXh0In1d">here</a></p><h3>Create the Monitor</h3><p>1. First, make sure you run the collection in the app with the new environment template. You’ll have to set up the environment as explained in the <a href="https://restful.io/music-discovery-with-spotify-and-postman-d230da418db7#.10724v4i0">previous post</a>.<br>2. Now head to <a href="https://monitor.getpostman.com/">Postman Monitors</a>. If you’re not already on Postman Pro, you can start a free trial.<br>3. Create a new monitor selecting the downloaded collection and environment template. In the screenshot, I’ve set it to run every morning at 9AM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6GmqaMw1V84Y6IH1JBSeQ.png" /></figure><p>4. Go to the details view, and you’ll see this screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIX5XyO7FHDtmvV3Z1AL1g.png" /></figure><p>5. Click on the Run Now button (next to Edit Monitor) to check if everything works fine.<br>6. Finally, after a few manual or scheduled runs, your monitor results should look something like this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asvySgFoZUa2B0H7MNudSA.png" /></figure><p>Since we’re using the Postman Pro API to update the environment in the final request, we constantly expand our list of artists as shown below. Personally, I have discovered entirely new and obscure genres using this monitor!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSyS9umY3N2AJM3fE3soZg.jpeg" /></figure><p><em>I hope you found this series to be useful and an insight into the hard work we’re putting into making Postman Pro the most comprehensive toolchain for API developers. Stay tuned for similarly fun use cases of the Postman ecosystem.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a020185ffec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/daily-mix-with-postman-monitors-and-spotify-3a020185ffec">“Daily Mix” with Postman Monitors and Spotify</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototyping APIs with Open API Specification and Node.js]]></title>
            <link>https://medium.com/the-restful-web/prototyping-your-api-project-with-the-open-api-specification-and-node-js-tools-7cb19f47f72d?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/7cb19f47f72d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Kalin Chernev]]></dc:creator>
            <pubDate>Tue, 21 Mar 2017 15:42:47 GMT</pubDate>
            <atom:updated>2017-03-21T16:04:31.680Z</atom:updated>
            <content:encoded><![CDATA[<p>A story about using Node.js community-built tools effectively in order to speed up the prototyping phase of your API project. In the whole article, <a href="https://github.com/OAI/OpenAPI-Specification">Open API specification</a> (which recently reached a RC on version 3) refers to version 2, also known as <a href="http://swagger.io/">Swagger specification</a>.</p><p>In this article I’ll briefly demonstrate how you can to make use of few community-driven tools which I came across recently and I definitely recommend: <a href="https://medium.com/u/67031c3182f8">Typicode</a>’s <a href="https://github.com/typicode/json-server">json-server</a> and <a href="https://medium.com/u/335ead3cb3ca">Rebilly</a>’s <a href="https://github.com/Rebilly/generator-openapi-repo">Open API generator</a>. By using a combination of them, you can quickly achieve a mock API server with really nice and useful documentation based in short deadlines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CB0acDqIYHo-wwwUZ9PaSQ.png" /></figure><h3>The <a href="http://generator-openapi-repo/">Open API generator</a>: specification is first</h3><p>I think it’s better to start with the specification as it answers many questions, even before making any real or fake data for the API.</p><p>The <a href="https://github.com/Rebilly/generator-openapi-repo/blob/master/README.md">official documentation</a> is sufficient to get started. There’s really no need for detailed tutorial here on how to use the tool in order to make a working project — just follow the steps. (And maybe push an empty commit on the gh-pages branch before first deploy just to make sure)</p><p>More importantly, you have to know why this generator is good and why I recommend it 😌</p><ul><li>It works with <a href="http://swagger.io/swagger-editor/"><strong>swagger editor</strong></a> out of the box, which feels like having a back-end for building your specification and documentation</li><li>Your specification (aka swagger spec) can be split into several files, which makes the project more manageable and mainteanable</li><li>Sleek documentation with <a href="http://swagger.io/redoc-openapi-powered-documentation/"><strong>ReDoc</strong></a> (though <a href="http://swagger.io/swagger-ui/">swagger-ui</a> is also generated) I think ReDoc is excellent in following the API documentation trends.</li><li>The results of your work can easily be deployed to <a href="https://pages.github.com/"><strong>github pages</strong></a>. It’s possible to make requests from here to external API server like the one we’ll have with json-server, as it supports CORS out of the box. Basically, as long as the server can accept requests from your github pages, these server really effectively as living documentation.</li><li>Continuous integration with <strong>Travis</strong> comes out of the box. Every time you push an update in the specification on the master branch, Travis checks for errors and deploys to github pages if everything is ok.</li></ul><p>When you follow the steps correctly, you’ll end up with a simplified version of <a href="https://github.com/Rebilly/RebillyAPI">RebillyAPI repository</a>. That’s the final outcome that’ll motivate you to try the generator now, if you haven’t already done so 😊</p><p>Probably you might find other similar tools such as <a href="https://github.com/sourcey/spectacle">spectacle</a>, however this tool worked really well for me and it covers everything I think one might need during a prototyping phase of an API project.</p><p>Thus, you have a tool to develop an Open API specification and deploy its documentation to github pages, making it nice and accessible for the public. With this Open API specification, you can later generate server/client code with <a href="http://swagger.io/swagger-codegen/">Codegen</a>, or just deploy the spec to services such as <a href="https://cloud.google.com/endpoints/docs/open-api-spec">Cloud Endpoints</a> or any other that will soon come with similar integration.</p><p>Basically, there are many opportunities available for you when you have the specification. Next step is to generate a server with mock data which matches the specification’s “contract” with the documentation or just any front-end app meant to work with the specification.</p><h3>The JSON server generator: fake it till you make it</h3><p>The <a href="https://github.com/typicode/json-server/blob/master/README.md">JSON server tool</a> is not really a generator per se, however it’s easy to integrate it as such in your toolchain. What I mean is, the tool is based on <a href="http://com/">express.js</a> and its popular middleware. You won’t need the express generator as you focus on the server. The endpoints are automatically discovered out of JSON files and you do not need express’ sophisticated templates views, routes, etc.</p><p>A simple <a href="https://github.com/typicode/json-server/blob/master/README.md#generate-random-data">function</a> in a script run by a npm task can easily do for having a generator for the server part. Also, <a href="https://www.npmjs.com/package/faker">faker</a> plays really well with this “generator” function. (no word play intended here) <a href="https://coligo.io/create-mock-rest-api-with-json-server/">Check an example</a>.</p><p>The main ideas you should understand with JSON server:</p><ul><li>It’s an easy start out of an example or existing JSON files</li><li>It’s easy to make a generator script to work with the tool</li></ul><p>Also, another benefit is that the server can be easily deployed. For example, if you decide to deploy on heroku, you’ll only need to update your server to use process.env.IP and process.env.PORT. The documentation points to the <a href="http://jsonplaceholder.typicode.com/">jsonplaceholder</a> example, but surely <a href="http://hook.io/">hook.io</a> or a similar cloud service will work just fine. Just keep it simple and working — the main idea of using this tool is to move fast and effectively.</p><p>Another option for generating a server on top of an existing specification is the <a href="https://www.npmjs.com/package/swagger-server">swagger-server</a> package which also integrates with express.js, however does not necessarily provide the ready filters, sorts, etc. that json-server does.</p><h3>Additional ideas</h3><p>I personally separated both tools in 2 repositories for the following reasons:</p><ul><li>The mock API server can be managed and deployed independently</li><li>Data from the mock server can be easily fetched from the github pages documentation, as JSON Server comes with CORS enabled by default</li><li>This same mock API server can be just thrown away when the real server comes into place to work with the documentation and/or application</li><li>It’s also good to have the documentation repository separate to make it easier to manage in a similar way as the server. Good example is how both swagger ui, swagger editor and ReDoc are integrated into a single project focusing on developing specification and documentation</li></ul><h3>Further notes</h3><p>That was a brief article sharing some love about open source projects which deserve an applause for being simple and effective helpers for developers.</p><p>If this article gets any positive feedback, I will make a follow-up story to this one showing few tips to improve the workflow of editing and publishing specification to documentation to a working API.</p><p>At any case, the search of more effective and well-integrated API prototyping, documentation and deployment continues.</p><p><em>If you thought this article was helpful, then consider recommending ❤ the story so more people will find it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cb19f47f72d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/prototyping-your-api-project-with-the-open-api-specification-and-node-js-tools-7cb19f47f72d">Prototyping APIs with Open API Specification and Node.js</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agile documentation for your API-driven project]]></title>
            <link>https://medium.com/the-restful-web/agile-documentation-for-your-api-driven-project-based-on-open-api-standards-11e54d4326bb?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/11e54d4326bb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Kalin Chernev]]></dc:creator>
            <pubDate>Mon, 23 Jan 2017 18:48:10 GMT</pubDate>
            <atom:updated>2017-02-20T18:06:50.697Z</atom:updated>
            <content:encoded><![CDATA[<h4>Based on <a href="https://www.openapis.org/">Open API standards</a></h4><blockquote>“Documentation is like sex; when it’s good, it’s very, very good, and when it’s bad, it’s better than nothing.” — Dick Brandon</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLHlW4oQi5Iz-4_V4NAEWA.jpeg" /><figcaption>Photo Credit: <a href="https://unsplash.com/@euwars"><em>Farzad Nazifi</em></a></figcaption></figure><p>The goal of this article is to inspire improved workflows for building and maintaining documentation for API-driven projects. In the end of the story, you will hopefully try out new approaches of documenting your code. As such, it automatically increases the value of your work through making it more maintainable and re-usable in less time and efforts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MDl1sVXRCbsiRY7muAsQ_A.png" /></figure><h3>Introduction</h3><p><a href="http://swagger.io/">Swagger</a> is one of the most popular and widely adopted specifications for RESTful APIs. In fact, the specification got off so well that <a href="http://swagger.io/open-source-integrations/">numerous community tools</a> are available. Also, the <a href="https://www.openapis.org/">Open API initiative</a> was born as a result of successful projects that use these tools basing on this specification in one way or another.</p><p>With the <a href="https://www.google.com/trends/explore?q=swagger%20api">raise of popularity</a> in 2016, leading experts started sharing advice on as <a href="https://scotch.io/tutorials/speed-up-your-restful-api-development-in-node-js-with-swagger">speeding the development phase with Swagger</a> and later making a <a href="https://scotch.io/tutorials/document-your-already-existing-apis-with-swagger">good documentation of an existing API</a>, again same spec being involved. These are few examples of well-written tutorials demonstrating benefits of having an API and a good toolchain, and documentation around it. There are <a href="https://egghead.io/courses/build-node-js-apis-with-openapi-spec-swagger">more</a>, of course, and I think this trend will stay solid for the next couple of years. That’s because the Open API specification makes sense just enough to empower developers and business people to have a common language of how an interface should work. It is as a contract of communication and data format between humans and machines.</p><p>In summary, the Swagger specification brings several clear advantages:</p><ul><li>We can <a href="http://editor.swagger.io/#/">write project specification</a> in yaml or json formats. The yaml one is probably closer to humans, which is really nice. (Yes, there are UI programs for that as well ;)</li><li>We can <a href="http://swagger.io/swagger-codegen/">generate server and client code automatically</a>, because when the specification is solid, the tools are solid too.</li><li>We can also <a href="http://swagger.io/swagger-ui/">generate live documentation</a> based on the same project specification. This is particularly useful and that’s why I’ll expand more on about this subject in this article.</li><li>We can program in many languages and the result of our work will stay alive longer, because it conforms to a server &lt;-&gt; client “contract”. Meaning, as long as you can make a swagger specification out of you work, you can move from one technology stack to another.</li></ul><p>Node.js is a popular choice for building the server part of applications, but it’s not the only one. The knowledge you can get from this article is transferable to almost any programming language.</p><h3>What makes a good API documentation</h3><p>Let’s now expand on the subject of having an effective documentation. There are many ways to document your software (and API), still, there are few major points which you have to cover to make it right. There is a common denominator of what makes one documentation better than another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*RV0AOyBUcpJ7vS1TuSx2ag.png" /></figure><p><strong>Auto-generation</strong></p><p>I think that is the most important one. Writing documentation should take the least amount of time and efforts, and should minimize the maintenance.</p><p>You have to find a good way to write the least amount of textual explanations for your API, which yields the highest value of practical guidelines for the user of the documentation.</p><p><strong>Include examples</strong></p><p>I speak from my personal experience here — it’s really pleasing when the documentation does not make me think too much. My advice: include some sample request objects, or some code samples, etc.</p><p>As a consumer or a developer of the API, I want to have a quick-gratification access to something that I use and it just works directly. Rarely I want to open my <a href="https://advancedrestclient.com/">advanced REST client</a> or <a href="https://curl.haxx.se/docs/">curl</a> while reading API documentation because it takes off my attention and is basically forcing me to get out of the page I’m reading in order to have “the real feeling” about how something works.</p><p><strong>Portable</strong></p><p>That is a feature I consider equally important for an effective piece of documentation. This is when the auto-generated code can be either displayed as a page or an embedded window of information. It also means that the result of your documentation is re-usable.</p><p>If you are a JavaScript developer reading this, you will know that how fascinating the number of possible view frameworks solutions are. One day we have to make a simple page with Bootstrap, then with React.js, Angular.js, Vue.js, etc. No matter the framework or the tool, integrating documentation in an app has to be as easy as an instantiation. (In order to keep the spirit of high productivity and low maintenance costs mentioned in one of the previous points)</p><p><strong>Swagger UI comes to the rescue</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dt246jpThKkFh7TPUva-9A.png" /></figure><p>Swagger UI is a widely-adopted solution to the problems above. The only drawback being that the markup generated by the tool is not <a href="http://getbem.com/introduction/">BEM</a>-ish or anything like this, thus preventing front-end developers to make really nice themes on top of the solution. (although it’s <a href="http://meostrander.com/swagger-ui-themes/">partially going on</a>)</p><p>When you look at the <a href="http://petstore.swagger.io/#/">demo</a> (or the editor), you will notice that there are similarities in the information presented.</p><p>Each endpoint of the API that is documented contains:</p><ul><li>Short description (the textual explanation we usually over-do)</li><li>Example samples of request bodies, options to change request types, etc.</li><li>Opportunity to try out the request &lt;-&gt; response operation</li></ul><p>On top of that, swagger-ui documentation is auto-generated based on a simple yaml or json swagger specification file. That is super-nice, because the specification that a business person writes or configures through an UI can serve as both a contract AND live documentation!</p><h3>We can do better than that</h3><p>Yes! Even after following popular tools and tutorials, I felt there is room for improvement. Mainly — writing the documentation itself.</p><p>See, the problem of writing a single specification file and then using tools to generate the documentation is easy until the maintenance comes into play. Imagine that the yaml spec is maintained by the same developer or development team that is responsible for the API endpoints of the app server. Surely, there will be back and forth between the specification file and the code files that contain the actual implementation. It takes extra time and efforts to stay focused while jumping between editors and making sure that both resources are well-matched.</p><p>In my opinion, the process of “specification &lt;-&gt; development &lt;-&gt; documentation &lt;-&gt; implementation” can improve. Namely, it is possible to do all them at once.</p><p>How? By writing swagger specification in the documentation blocks of our code and plugging watch tasks in-between! Yes, the specification might still be in ownership of another one, not the developer. But even then — what if can just see live documentation based on the comments we’re placing in our code? Wouldn’t it be a motivating factor to write better in-code documentation? What is more, wouldn’t it be easier for developers to maintain both the code and the documentation of endpoints where the two are just next to each other?</p><p>Look at the following piece of code:</p><pre>/**<br> * @swagger<br> * /login:<br> *   post:<br> *     description: Login to the application<br> *     produces:<br> *       - application/json<br> *     parameters:<br> *       - name: username<br> *         description: Username to use for login.<br> *         in: formData<br> *         required: true<br> *         type: string<br> *       - name: password<br> *         description: User&#39;s password.<br> *         in: formData<br> *         required: true<br> *         type: string<br> *     responses:<br> *       200:<br> *         description: login<br> */<br>app.post(&#39;/login&#39;, (req, res) =&gt; {<br>  ... <br>});</pre><p>As you might have already guessed, this is a sample from <a href="https://github.com/Surnet/swagger-jsdoc">swagger-jsdoc</a> which takes the contents of the text after @swagger and parses the contents of the <a href="http://usejsdoc.org/">jsdoc</a> documentation into a <a href="http://swagger.io/specification/">swagger specification</a>. This specification can be then visualized, for example, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*K0swMwFEVHWqtcXnkxf0zg.png" /></figure><p>It’s true that I made the screenshot from the built of the example, not from this tiny sample, but you get the point ;) (Continue reading and you will see much nicer interface of the same info)</p><p>Since I’m looking to improve this workflow even further (and make it more fun for developers to use the tool), I recently suggested a watch task in swagger-jsdoc command line tool that works just like this:</p><pre>$ swagger-jsdoc -d swaggerDefinition.js routes.js routes2.js -w</pre><p>In this case, after having a generated swagger.json the command line will continue listening for changes in routes.js and routes2.js and then re-generate the specification swagger.json on updates.</p><p>Also recently, the command line tool got a new feature to output yaml if the -o flag is used like this:</p><pre>$ swagger-jsdoc -d swaggerDefinition.js apis.js -o swagger.yaml</pre><p>In this case, apis.js will be searched for @swagger tags, but the parsed specification will be written to swagger.yaml file.</p><p>Having the swagger.json or swagger.yaml specification at this moment is a nice start. This file is the key re-usable resource that can be integrated with other tools such as swagger-ui which visualize the “soul” of the API in nice UI interfaces.</p><h3>Improved API documentation workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7cg9JrmXIPer1w8IXg_jnQ.png" /></figure><p>Some time ago, an article about <a href="https://javascriptkicks.com/stories/94009/watching-file-changes-with-npm-scripts">watching files changes with npm scripts got popular</a>. I believe there is a reason why comments are not possible under the original article, but never mind, it got me on the path of researching the <a href="https://nodejs.org/docs/latest/api/fs.html#fs_fs_watch_filename_options_listener">fs.watch()</a> and its behavior. After experimentation I reached to prefer <a href="https://www.npmjs.com/package/chokidar">chokidar</a> which is a module improving the fs.watch() interface. In fact, I liked chokidar so much that I took the opportunity to suggest a <a href="https://github.com/Surnet/swagger-jsdoc/releases/tag/v1.9.0">new feature in the CLI tool of </a><a href="https://github.com/Surnet/swagger-jsdoc/releases/tag/v1.9.0">swagger-jsdoc</a> which is, duh, a watch task working with the API files. (Briefly mentioned in the previous chapter)</p><p>The chokidar module is also an integral part of the <a href="https://www.npmjs.com/package/browser-sync">browser-sync</a> module which, in turn, an already mature and battle-tested piece of software. It is widely adopted in various products and projects to increase development experience and productivity.</p><p>Having this understanding, I saw another opportunity — making a simple integration between instruments which integrate the chokidar module. I only needed a better understanding of <a href="http://swagger.io/swagger-ui/">Swagger UI</a> which is the “glue”, or the “contract”, between the back-end server side (the API) and the front-end (client) side. I feel it’s comfortable (and smart) that the documentation pages are the first-hand client and consumer of the API. Also, I believe that this consumer should be easy to make and maintain, but still really nice-looking, so that there is something pleasant for our paying clients to see. With browser-sync Swagger UI got a bit more fun to work with.</p><p>In order to demonstrate the idea better in visual and kinesthetic way, I created a <a href="https://github.com/kalinchernev/agile-open-api-docs">supplementary repository</a>. It contains examples of the first approach that came to my mind keeping <a href="https://en.wikipedia.org/wiki/KISS_principle">the KISS principle</a>. Basically, there are few npm scripts that make the system work together.</p><p>First, you can have a look at <a href="https://github.com/kalinchernev/agile-open-api-docs/blob/master/package.json">the </a><a href="https://github.com/kalinchernev/agile-open-api-docs/blob/master/package.json">package.json manifest</a>. Tasks are separated in two main categories: tasks for the server side (the API) and tasks related to the documentation. For the API development part, npm run api fires a server with nodemon and swagger-jsdoc As a result, any changes in the api/ folder trigger server restart and re-generation of swagger.json specification which goes to api-docs/ folder.</p><p>Secondly, the npm run docs:develop task fires a browser-sync server for the client side serving the api-docs/ folder which receives automatically updated swagger.json specification from the previous task. You can run those two tasks in separate terminal sessions or just create another parallel task following the examples of the package.json file with npm-run-all.</p><p>At this stage, you can freely update both the server and client sides of your project having near real-time feedback and results visible in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*6bMTxVkYaUEEjyqpeiXBRA.png" /><figcaption>Even the bare minimum of defining an Open API specification can be visualized in a good way.</figcaption></figure><p>You might be wondering — why isn’t this the interface of Swagger UI I am used to seeing around! What happened? Well, I used a <a href="https://github.com/jensoleg/swagger-ui">fork which looks nicer</a>. Here’s an <a href="http://swaggerui.herokuapp.com/?url=http://petstore.swagger.io/v2/swagger.json#!/pet/addPet">online demo</a> which you can play with to get the feeling of what your documentation may look like after you enjoyably use swagger-jsdoc and browser-sync as shown in <a href="https://github.com/kalinchernev/agile-open-api-docs/blob/master/package.json">this repository.</a></p><p>The same workflow is possible with other file extensions such as .php just changing the input parameters and removing the binding to the nodemon server restart task, so that another standalone server is used instead. Here’s an example taken from a recent pull request which was included in swagger-jsdoc to parse swagger documentation to yaml output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W72Xll_3kHjiCtNkb7U3qg.png" /></figure><h3>Deployment</h3><p>I have intentionally left out the deployment part out of this story, because I believe there are many good options on the market and it really depends on the personal preferences how to manage this part of the process. For example, you can follow the scotch.io tutorial mentioned earlier to place the docs on heroku, or you can also include an npm script which works with <a href="https://github.com/tschaub/gh-pages">gh-pages</a> to deploy the assets directly to your repository, etc. The main thing is that the api-docs folder is already built and ready to be deployed as-is.</p><p>Myself, I plan to experiment with <a href="https://cloudplatform.googleblog.com/2016/09/manage-your-APIs-with-Google-Cloud-Endpoints.html">Google Endpoints</a> in near future although it’s a new service. That’s because it supports the <a href="https://cloud.google.com/endpoints/docs/open-api-spec">Open API specification</a> and provides flexible options on deployment for both the API and the documentation on reasonable terms. An interesting point to notice is that the service guidelines show deployment only of the swagger/openapi specification file which can be generated by the swagger-jsdoc This is a good example of re-using single specification for multiple purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*QHvYcf7gyUyIwNlBo-jHTQ.png" /></figure><h3>Conclusions</h3><p>Writing this article and sharing some code around it, I’m integrating tools that solve problems which have already been under the radar of the <a href="https://medium.com/u/40cf4ae0a767">API Evangelist</a> such as <a href="https://apievangelist.com/2015/02/02/we-need-better-api-documentation-and-ui-deployment-options/">the need of better API documentation and UI deployment</a> which was later followed up by findings about <a href="https://apievangelist.com/2015/06/27/the-responsive-swagger-driven-version-of-slate-api-documentation-i-was-looking-for/">improved Swagger UI design solution</a>. Few months ago, there was also a <a href="https://apievangelist.com/2016/09/16/learning-from-the-success-of-swagger-ui/">reflection article about the success of Swagger UI</a>.</p><p>I hope that this article has inspired you to consider some new ways to improve your documentation workflows for your API project. I know that the idea of automated documentation generation with swagger tools is not new. Rather, I aim to introduce some new ideas on solving the problems which have been around on topic for a while with the tools available today to improve productivity.</p><p>The tools shown in <a href="https://github.com/kalinchernev/agile-open-api-docs">the repository</a> are free and vendor-neutral and the documentation build can be deployed to any place which serves you best. So, I encourage you to further experiment with the code and adapt it to work best for your specific needs.</p><p><em>If you thought this article was helpful, then consider recommending ❤ the story so more people will find it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11e54d4326bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/agile-documentation-for-your-api-driven-project-based-on-open-api-standards-11e54d4326bb">Agile documentation for your API-driven project</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Music Discovery with Spotify and Postman]]></title>
            <link>https://medium.com/the-restful-web/music-discovery-with-spotify-and-postman-d230da418db7?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/d230da418db7</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[oauth]]></category>
            <dc:creator><![CDATA[Ankit Sobti]]></dc:creator>
            <pubDate>Mon, 05 Dec 2016 00:50:50 GMT</pubDate>
            <atom:updated>2016-12-04T13:26:13.895Z</atom:updated>
            <content:encoded><![CDATA[<p>This continues from my previous post in the series <a href="http://medium.com/@sobtiankit/conditional-workflows-in-postman-f79c05306671">Conditional Workflows in Postman</a>. We will continue to focus on Postman Collections and elaborate on <a href="http://blog.getpostman.com/2016/06/14/introducing-postman-runtime-more-power-better-control/">Postman Runtime</a>.</p><p>Today, we are going to create our own on-demand playlist using the <a href="https://developer.spotify.com/web-api/">Spotify API</a> and Postman Collections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZKv0hmvTob7nfTMIqfe3A.png" /></figure><p>I love <a href="http://www.spotify.com/">Spotify</a>. Over the years it has helped me discover great music. Discover Weekly, in particular, has made me look forward to Monday mornings, with some amazing curated music delivered to the app. Usually, when I come across a great new artist, I look for their top songs and when a bit more adventurous, check out the related artists and repeat the process. Quickly jotting this down into a workflow:</p><p>1. Choose the artist(s) that you like.<br>2. Randomly choose one (let’s say The Who) from the list and GET the meta information using Spotify API<br>3. Get artists related to The Who and choose a random 5<br>4. Create a playlist named “The Who Mix”<br>5. GET the most popular songs from The Who, choose a random 5 and add to the playlist<br>6. For each related artist, do the same</p><p>And that’s it! We get a brand new playlist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8HfAvc-EXj6oNQsZ2SzKg.png" /></figure><p>Click the Run in Postman button below to get the Collection and Environment in your <a href="https://www.getpostman.com/apps">Postman app</a>.</p><p>You can check out the documentation for the collection <a href="https://documenter.getpostman.com/view/583/spotify-playlist-generator-v1/2MtDWP">here</a> and download the collection <a href="https://app.getpostman.com/run-collection/e0d1cf95318b625a6a6b#?env%5BSpotifyGenV1.template%5D=W3sidHlwZSI6InRleHQiLCJlbmFibGVkIjp0cnVlLCJrZXkiOiJhcnRpc3RzIiwidmFsdWUiOiIifSx7InR5cGUiOiJ0ZXh0IiwiZW5hYmxlZCI6dHJ1ZSwia2V5IjoiTiIsInZhbHVlIjoiNSJ9LHsidHlwZSI6InRleHQiLCJlbmFibGVkIjp0cnVlLCJrZXkiOiJ1c2VyX2lkIiwidmFsdWUiOiIifSx7InR5cGUiOiJ0ZXh0IiwiZW5hYmxlZCI6dHJ1ZSwia2V5IjoiY291bnRyeV9jb2RlIiwidmFsdWUiOiJVUyJ9LHsidHlwZSI6InRleHQiLCJlbmFibGVkIjp0cnVlLCJrZXkiOiJjbGllbnRfaWQiLCJ2YWx1ZSI6IiJ9LHsidHlwZSI6InRleHQiLCJlbmFibGVkIjp0cnVlLCJrZXkiOiJjbGllbnRfc2VjcmV0IiwidmFsdWUiOiIifSx7InR5cGUiOiJ0ZXh0IiwiZW5hYmxlZCI6dHJ1ZSwia2V5IjoicmVmcmVzaF90b2tlbiIsInZhbHVlIjoiIn1d">here</a>:</p><h4><strong>Setup the Environment</strong></h4><ol><li><strong>Spotify</strong></li></ol><p>a. Head to <a href="https://developer.spotify.com/">Spotify Developer</a> and register, then create a new app in the My Applications section. Add the `client_id` and `client_secret` to your environment.<br>b. Under the newly created app config, add the following Redirect URI — “<a href="https://www.getpostman.com/oauth2/callback">https://www.getpostman.com/oauth2/callback</a>&quot;<br>c. We’ll use the <a href="https://developer.spotify.com/web-api/authorization-guide/#authorization-code-flow">Authorization Code Flow</a> to obtain the Refresh Token.<br>d. Open Postman, under a new request, click on the Authorization tab, select OAuth 2.0 and fill in these values:</p><blockquote>Token Name: can be anything<br>Auth URL: <a href="https://accounts.spotify.com/authorize">https://accounts.spotify.com/authorize</a><br>Access Token URL: <a href="https://accounts.spotify.com/api/token">https://accounts.spotify.com/api/token</a><br>Client ID: {{client_id}}<br>Client Secret: {{client_secret}}<br>Scope: playlist-read-private playlist-modify-private<br>Grant Type: Authorization Code<br>Request access token locally: Checked</blockquote><p>Click on Request Token, go through the OAuth flow, and add the <em>refresh_token</em> to your environment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*fcl4gxs9BaGb9AkmuEdvAA.png" /></figure><p><strong>2. Environment Config</strong><br> <br>Set the following variables in your environment<br>a. <em>user_id</em>: your spotify username<br>b. <em>country_code</em>: in <a href="http://en.wikipedia.org/wiki/ISO3166-1alpha-2">ISO 3166–1</a> format<br>c. <em>N</em>: defaults to 5. Refer to the algorithm section for more details<br>d. <em>artists</em>: List of seed artists for the collection. You can find them as part of the Spotify artist link (Available in the app): e.g. for Oasis, the link looks something like <a href="https://open.spotify.com/artist/2DaxqgrOhkeH0fpeiQq2f4">https://open.spotify.com/artist/2DaxqgrOhkeH0fpeiQq2f4</a>, choose the last section. The artists variable needs to be set up as an array of strings, that is, with square brackets and double quotes. So it’ll look something like: [“2DaxqgrOhkeH0fpeiQq2f4”, “2ooIqOf4X2uz4mMptXCtie”]</p><p><strong>3. Run the Collection</strong></p><p>a. Now run the collection in the Postman app using the <a href="https://www.getpostman.com/docs/running_collections">Collection Runner</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*iZxTevv4KKGg6ZGHQ6HlpQ.png" /></figure><p>By keeping Persist Variables checked, the next time we run this collection, it will add the newly discovered Related Artists to the original seed and thus expanding the scope of discovery, each time we run this collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQpz6fb-FKpTQzII8qLyag.png" /></figure><p>b. The same collection executes in <a href="https://github.com/postmanlabs/newman">Newman</a> as well. Just export the Collection and Environment files and execute the following command</p><blockquote>newman -c SpotifyPLGen.json.postman_collection -e SpotifyPlGen.json.postman_environment</blockquote><p>In the final post of this series, we will schedule this collection to run every week for that true <em>Discover Weekly</em> experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d230da418db7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/music-discovery-with-spotify-and-postman-d230da418db7">Music Discovery with Spotify and Postman</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webhooks do’s and dont’s: what we learned after integrating +100 APIs]]></title>
            <link>https://medium.com/the-restful-web/webhooks-dos-and-dont-s-what-we-learned-after-integrating-100-apis-d567405a3671?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/d567405a3671</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Giuliano Iacobelli]]></dc:creator>
            <pubDate>Tue, 22 Nov 2016 16:01:01 GMT</pubDate>
            <atom:updated>2016-11-23T17:21:39.807Z</atom:updated>
            <content:encoded><![CDATA[<p>As modern applications are becoming more and more a composite of APIs and the serverless architectures are getting more attention, API providers can’t afford any longer to expose only traditional REST endpoints.</p><p>Traditional REST API are designed for when you want to allow a programmatical retrieve or post content, far from being optimal when you just want your application to be told when something changed. If that is the case, it would require polling at regular intervals, and that just doesn’t scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEmrcTajSG5A4Z_JjrGqfw.png" /><figcaption>Picture credits <a href="https://medium.com/u/e6dd3fdb7c2d">Lorna Mitchell</a></figcaption></figure><p>Polling an API is generally a wasteful and messy way of trying to retrieve that piece of information. Some events may only happen once in a while, so you have to figure out how often to make the polling calls, and you might miss it.</p><blockquote>Don’t call us, we’ll call you!</blockquote><p>Well webhooks are the answer. <strong>A webhook is a way for web service to provide other services with near real-time information using HTTP POST requests.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8t-MNjY-6rJ79rsDnZt0rA.png" /><figcaption>Picture credits <a href="https://medium.com/u/e6dd3fdb7c2d">Lorna Mitchell</a></figcaption></figure><p>A webhook delivers data to other applications as it happens, meaning you get data immediately. This makes webhooks much more efficient for both the provider and the consumer, if your API doesn’t support them you should really do something about it (you hear me <a href="https://medium.com/u/f4fb2a348280">Salesforce</a>?).</p><p>When it comes to designing webhooks there is nothing really close to a standard in the HTTP API literacy. Every service implements webhook differently leading to many different flavors of webhooks implementations out there.</p><p>After integrating APIs from more than 100 different services I can tell that the way a service exposes webhooks can be a deal breaker. So here are the things that make us happy when we need to integrate with a service exposing webhooks.</p><h4>Self explanatory and consistent</h4><p>A good webhook service should provide as much information as possible about the event that is being notified, as well as additional information for the client to act upon that event.</p><p>The POST request should contain a timestamp and webhook_id if one was given by the client when creating it. A type attribute should be included if you&#39;re providing different types of webhooks whether or not they are being sent to a single endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Yi85OX2kNJw-bbn8O0VVQQ.png" /><figcaption>Sample of Github’s webhook payload</figcaption></figure><p><a href="https://medium.com/u/d18563e4f2b9">GitHub</a> does that perfectly. Please don’t send just an ID that has to be resolved with another API request like Instagram or Eventbrite do.</p><p>If you think your payload is too heavy to be sent all at once give me the chance to make it lighter.</p><p><a href="https://medium.com/u/3ecae35d6d66">Stripe</a>’s <a href="https://stripe.com/docs/api">event types</a> are a good example of this done well.</p><h4>Allow consumers to define multiple URLs</h4><p>When you build your webhooks you should think about the people on the other end of the wire that have to receive your data. Giving them the chance to subscribe to events under one single URL is not the best developer experience that you can offer. If I need to listen for the same event across different systems I’m going to end up in troubles and I need to put in between some Reflector.io type of thing. <a href="https://medium.com/u/ce5450a7b906">Clearbit</a> please you have such good APIs, step up your webhook game accordingly.</p><p><a href="https://medium.com/u/7ca8972daf76">Intercom</a> does this very well giving you the chance to add multiple URLs and define for each one of them the events that you want to listen for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGfFqT7G4x3swfm1qkxjfA.png" /><figcaption>Webhook management panel on Intercom</figcaption></figure><h4>UI based subscription vs API based subscription</h4><p>Once the integration is in place how should we handle the creation of an actual subscription? Some services opted for a UI that guides you through the setup of a subscription some others built an API for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*lQ5VTo4IF50IjaimPq-F4Q.png" /></figure><p><a href="https://medium.com/u/26d90a99f605">Slack</a> killed it by supporting both.</p><p>It provides a slick UI that makes creating subscription very easy and exposing a solid Event API (which still doesn’t support as much events as their Real Time Messaging API does but I’m sure they’ re working on it).</p><p>An important thing to keep in mind when choosing whether or not providing an API for your webhooks is at what scale and granularity your subscriptions are going be available and who is going to configure them.</p><p>I find it curious that a tool like <a href="https://medium.com/u/772bf2413f17">MailChimp</a> forces a non technical audience to mess with webhooks configurations. By making webhooks available via API, any third-service (e.g. Stamplay, Zapier or IFTTT) that has a Mailchimp integration could just make that happen programmatically and build better user experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*EEMaCdPa63smJ3oOSpQ60w.png" /></figure><p>For creating new webhooks subscriptions via API, you should treat the <em>subscription</em> like any other resource in an HTTP API.</p><p>A very good one we’ve been working with recently is the completely renewed webhook implementation made by the Box team which was released <a href="https://blog.box.com/blog/box-webhooks/">this summer</a>.</p><h4>Securing webhooks</h4><p>Once someone configured his service to receive payloads from your webhook, it’ll listen for any payload sent to the endpoint.</p><p>If consumer’s application exposes sensitive data, it can (optionally) verify that requests are generated by your service and not a third-party pretending to be you. This isn’t required, but offers an additional layer of verification.</p><p>There are a bunch of ways to go about this — if you want to put the burden on the consumer side, you could opt to give him a whitelist requests from IP address — but a far easier method is to set up a secret token and validate the information.</p><p>This can be done at different degrees of complexity starting from a plain text shared secret like Slack or Facebook do</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qyzDKFf4CfPwJEozGIah0w.png" /></figure><p>To more complex implementations. As an example Mandrill signs webhook requests including an additional HTTP header with webhook POST requests, X-Mandrill-Signature, which will contain the signature for the request. To verify a webhook request, generate a signature using the same key that Mandrill uses and compare that to the value of the X-Mandrill-Signature header.</p><h4>Subscriptions with expiration date</h4><p>The odds to face an integration of a service that exposes subscriptions with an expiration date is not very high today but we can see this becoming a more common feature. Microsoft Graph API is an example. Any subscription you perform over API expires 72hours later unless you renew it.</p><p>From a data provider standpoint it makes sense. You do not want to keep sending out POST requests to services that could be no longer up and running or interested in your data but for all those who are actually interested it’s an unpleasant surprise. You’re Microsoft: if you can’t afford the heavy lifting who is supposed to do it?</p><h4>Conclusions</h4><p>The webhook landspace is still fragmented but common patterns are eventually coming up tough.</p><p>At <a href="https://stamplay.com/"><strong>Stamplay</strong></a> API integration is a thing. We face the integration challenges on a daily basis and OpenAPI specifications like Swagger, RAML or API Blueprint can’t help because none of them supports webhook scenarios.</p><p>So if you’re thinking about implementing webhooks I invite you to think about their consumption and look at examples like <a href="https://medium.com/u/d18563e4f2b9">GitHub</a>, <a href="https://medium.com/u/3ecae35d6d66">Stripe</a>, <a href="https://medium.com/u/7ca8972daf76">Intercom</a> and <a href="https://medium.com/u/272cd95a3742">Slack API</a>.</p><p>PS. <a href="https://medium.com/u/504c7870fdb6">Medium</a> any plans for webhooks? Come on, RSS feeds are so old school.</p><p><strong>Update</strong>: Medium actually does provide a way to get realtime notifications through <a href="http://medium.superfeedr.com/">http://medium.superfeedr.com/</a> 👌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d567405a3671" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/webhooks-dos-and-dont-s-what-we-learned-after-integrating-100-apis-d567405a3671">Webhooks do’s and dont’s: what we learned after integrating +100 APIs</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying API documentation for a great first user experience]]></title>
            <link>https://medium.com/the-restful-web/simplifying-api-documentation-for-a-great-first-user-experience-40a171d57d66?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/40a171d57d66</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Abhinav Asthana]]></dc:creator>
            <pubDate>Tue, 03 May 2016 05:32:06 GMT</pubDate>
            <atom:updated>2016-05-03T05:32:06.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*UCeWE0jnHXd_Y4I6.jpg" /><figcaption><em>Originally published at </em><a href="http://blog.getpostman.com/2016/04/25/simplifying-api-documentation-for-a-great-first-user-experience/?utm_content=buffer727ac&amp;utm_medium=social&amp;utm_source=twitter.com&amp;utm_campaign=buffer"><em>blog.getpostman.com</em></a><em> on April 25, 2016.</em></figcaption></figure><p>Introductions to languages or software systems usually start with a “Hello World” exercise but most APIs are reference manuals only useful for experts. The docs are the first step in a beginner’s learning curve. However with API documentation the developer usually sees a long list of API endpoints in one single page that makes it really hard to get started with the API. It is my belief that API documentation should be similar to learning programming — explaining basic concepts with specific examples. As someone builds up their skill levels, they can use code to solve more complex real world problems.</p><p>How do you go about building a great first user experience? Being Postman, we’ve been exposed to several ways in which API publishers approached this problem. Below is a list of questions to help you think through the process of making your API simpler to understand and faster to use.</p><p>In part 2 of this post, we’ll talk about our approach at Postman to solving some of these problems with examples and a more in-depth analysis of specific documentation.</p><p><strong>Step 1. Who is your user?</strong></p><p>Users for your API documentation will come from different backgrounds. They might be backend developers, frontend developers, testers or architects. They’ll know different programming languages and different frameworks. Talking in their “language” will help you get your point across. But everyone’s language is different. Navigating the paradox is critical. Having a range of examples in different programming languages is important — don’t assume everyone knows Java and XML.</p><p><strong>Step 2. What does your API do?<br> </strong><br> Is this API itself the product? Or is this a way for consuming/storing information created in your app? Explaining how your API can make someone or something better will help set an anchor point. At this point it is critical to describe what your API does NOT let someone do saving the user a lot of time and frustration.</p><p><strong>Step 3. How does one access your API?</strong></p><p>This is where a lot of users get stuck. Getting an authorization token easily <em>for the appropriate access level</em> will help someone try out the API quickly. You can do this by generating an access token automatically for a user if he is signed into your developer portal or your website. You can also create a token management interface similar to Github that can provide users with both flexibility and security. You should have a separate section for authorization against production use cases and how to properly secure a service.</p><p><strong>Step 4. How can someone quickly use your API?</strong></p><p>Draw out common use cases and “Hello MyAPI” samples. You might solve the majority of problems for your first user right here. This might be a basic how-to on getting and fetching data, on combining different end-points or even a cool use case that might be buried inside your reference docs. Knowing your user (See point 1 above) will help a lot.<br> <strong><br> Step 5. How can someone integrate your API?</strong></p><p>Your API will be used with other internal or public APIs. Examples of how to combine your API with other data sources, data elements to look for inside JSON bodies to transfer data, or other common workflows that your users might want to be aware of.<br> <strong><br> Step 6. What is the extent of your API?</strong></p><p>Finally, write reference documentation for your API. API references should describe possible request and response types — not just the most common one. Sample code in the user’s choice of language will help him run the API docs quickly.<br> <strong><br> Step 7. Where does someone ask for help?</strong></p><p>What happens when things don’t work as expected? Where does the user ask for help? Linking to an FAQ, your support channel or your community page will help the user get unstuck faster.</p><p><strong>Conclusion</strong></p><p>API documentation is a complex undertaking. Thinking about your user’s first experience of your documentation will help them get started faster and your API’s value more apparent. Creating reference documentation is great but there are several components that I encourage you to consider.</p><p><strong>References</strong></p><ul><li><a href="http://norvig.com/21-days.html">Teach Yourself Programming in Ten Years</a> is a great reference that talks about learning by doing</li><li><a href="https://jacobian.org/writing/what-to-write/">What to Write</a> says that a well-documented project needs to have different forms of documentation</li></ul><p><em>Originally published at </em><a href="http://blog.getpostman.com/2016/04/25/simplifying-api-documentation-for-a-great-first-user-experience/?utm_content=buffer727ac&amp;utm_medium=social&amp;utm_source=twitter.com&amp;utm_campaign=buffer"><em>blog.getpostman.com</em></a><em> on April 25, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a171d57d66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/simplifying-api-documentation-for-a-great-first-user-experience-40a171d57d66">Simplifying API documentation for a great first user experience</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Objects at REST, Part 1: What Is It?]]></title>
            <link>https://medium.com/the-restful-web/objects-at-rest-part-1-what-is-it-3e26f0978616?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/3e26f0978616</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Stu]]></dc:creator>
            <pubDate>Sat, 23 Apr 2016 22:34:38 GMT</pubDate>
            <atom:updated>2016-04-23T22:37:38.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23u-G4pkQ7Yxb__jt05JEw.png" /><figcaption>Photo by<br><a href="https://unsplash.com/photos/inh3oOPOOjQ">Aliis Sinisalu</a></figcaption></figure><p>Okay, so, it’s 2016 and you don’t know what REST is, what an API is, or how to design an API with this magical thing called REST that everyone keeps talking about. You’re frustrated by the phrase “Just Use REST,” because when you go to find resources on the topic, they’re hard to discover if you don’t know what to search on Google.</p><p>I’ll start this off with a short story. I graduated from university and somehow still had <em>no idea</em> what an API was. It wasn’t because I was lazy and never learned it, but more so the fact that it’s not really something that was talked about often at school. Then, I went looking for jobs, and all of the postings started talking about Web APIs, REST, and that I should have an understanding of it.</p><p>Turns out, <em>this is a foundational concept</em> that many jobs in tech require their staff to understand now. So why did I never learn it in school? I don’t really know (I really don’t have an answer, but it seems Comp Sci programs struggle to keep up with the latest tech like boot camps do), but needless to say I set out to learn all about RESTful APIs. I now want to pass that knowledge on to anyone who finds themselves in a similar situation.</p><blockquote>I graduated from university and somehow still had <em>no idea</em> what an API was.</blockquote><p>The goal, ultimately, of this mini-guide is to help you get up to speed with an industry best practice that you <em>should know</em>.</p><h4>What This Guide Is Not:</h4><p>A fully fledged, granular guide on REST and APIs. That would just require so much detail, and probably not the most suited to a series of <em>Medium</em> articles.</p><h4>What This Guide Is:</h4><p>A get-up-to-speed guide on REST and APIs…the “essentials,” if you will, to modern API design in 2016. I will explain a lot of details, and if you want to learn more, I will provide my sources for what I would approve as excellent next steps in the RESTful API learning process.</p><h4>Structure of the Article:</h4><ul><li>Glossary of Terms</li><li>What is an API, and what is REST?</li><li>Common Conventions / RESTful Principles</li><li>REST Interface Constraints</li><li>Summary So Far</li></ul><h4>Glossary of Terms</h4><p>Before we really get started, I want to supply you with a few key terms I’ll be using in the rest of the article. This will help you understand what I mean when I mention certain concepts.</p><ol><li><strong>Hypermedia:</strong> As described by <a href="https://en.wikipedia.org/wiki/Hypermedia">Wikipedia</a>, Hypermedia “is a nonlinear medium of information which includes graphics, audio, video, plain text and hyperlinks.”</li><li><strong>Resource: </strong>In RESTful APIs, resources are identifiers to any piece of interesting information the server can provide. For example, a resource could be the users of a system, a user’s timeline of posts, or a blog post, like this one. A practical example is twitter.com/<strong>Stuart_Weir</strong>, where my name is the identifier of a user resource in Twitter’s servers.</li><li><strong>URI / URL:</strong> URI stands for Uniform Resource Identifier, which is simply a set of characters that is used to identify a resource. As we saw above, twitter.com<strong>/Stuart_Weir </strong>is a resource, but this resource is <em>identified</em> by a URI. A URL, or Uniform Resource Locator, is the most commonly used version of a URI, and is often called a web address. The whole of <strong>twitter.com/Stuart_Weir</strong> is the URL.</li><li><strong>State:</strong> this is a pretty straight-forward term, but quite simply, it’s used to explain the current “state” or “context” of an application. In RESTful APIs, Hypermedia (see #1) is used as the <em>engine</em> <em>of application state</em>.</li><li><strong>Media Types and Content-Type: </strong>A Media Type is the specified data format that will be sent in the Request / Response of a client-server exchange. A Content-Type is the HTTP Header field used to specify the Media Type. For example, <strong>Content-Type: application/json</strong> would be in the HTTP Header field, that specifies a Media Type of <strong>application/json</strong>.</li><li><strong>Request / Response:</strong> A Request / Response is an interaction between the client and the server. The client will send a request to the server to do something, or get some data, and will wait for a response from the server on the status of that request, along with any extra data pertaining to that request.</li></ol><p>To sum all this up, let’s quickly use all these terms in an example. A client (my web browser), sends a request to the URL www.twitter.com, specifying a Media Type in the HTTP Header field, “Content-Type.” Twitter responds to my request with an HTTP status specifying that everything went okay, and the data my browser requested (the web page). From this web page, I have a few options. I can post a new tweet, I can go to my profile, etc. Let’s say I want to go to my profile page. I click on my profile, and this sends another request from my browser (the client) to the server with the Hypermedia link www.twitter.com/Stuart_Weir. Notice that my request was for twitter.com, with the /Stuart_Weir resource appended. Twitter’s server sees that “yes, I have this resource,” and sends it back to my web browser, where I see my profile page.</p><p>For a more full-fledged glossary of API terminology, I <em>highly recommend</em> taking a look at Mashape’s <a href="http://apiglossary.com/"><em>API Glossary</em></a>. This is an incredibly useful resource for reference, and created by what I like to call the “King Kong of APIs,” <a href="https://www.mashape.com/"><em>Mashape</em></a>.</p><p>Now that we have a bit of foundation laid out in terms of terminology, let’s get to the heart of this article.</p><h4>What is an API, and what is REST?</h4><p>An API is an Application Programming Interface. This sounds super technical, but it actually really isn’t. It’s essentially an interface for programmers, much like a User Interface (UI) is an interface for product users.</p><p>To give a quick example, when someone directs their browser to twitter.com, it takes them to a UI that allows them to do a few things. Twitter will ask them to log in or sign up, and from there the UI will change/update so that the user can do even more things with the service.</p><p>Much like the Twitter example, APIs are essentially a more technical version of this. RESTful APIs expose resources (see above) that a programmer can interact with. APIs (and RESTful APIs more specifically) should be easy to use and easy to discover. In other words, like when a user goes to Twitter, the user should understand how to use Twitter, and discover different features of Twitter easily. In the same way, great RESTful APIs allow programmers to easily use their features, and discover the API quickly.</p><p>REpresentational State Transfer (REST) offers a way to structure APIs and offers certain opinions and conventions that make building APIs easier, more efficient, and standard, so that a client user (a programmer wishing to use that API), can quickly get up to speed with the API simply by understanding it follows certain conventions. REST was first introduced in Roy Fielding’s dissertation, <em>Architectural Styles and the Design of Network-based Software Architectures. </em>For a full overview of REST as fielding defined it, please check it out <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">here</a>.</p><p>REST is a stateless, client-server architecture that offers a cache-able protocol, and it’s almost always implemented via HTTP. It typically uses HTTP methods for Create, Read, Update, and Delete (CRUD) operations, and as such, is standards based. We’ll get into the definition of some more of this terminology later. REST is also language independent, meaning it can be implemented in numerous programming languages, so a REST API server built in Ruby, for example, can be consumed by a Go(lang) client. If we’re to follow with this Ruby and Go example, you may be wondering, “how does data written with Ruby code transfer to data that Go can understand?” Good question, but I’ll get to that in a later post.</p><p>Okay, so what else is there to know about REST? For now, let’s quickly sum up what we just learned about APIs and REST. An API is an Application Programming Interface, which is essentially software that exposes some functionality that other software can consume. In RESTful APIs, this is built off of a client-server architecture that we’ll take a look at in more detail in a moment. REST allows for us to transfer the representational state of a resource from the client to the server, and vice versa. Moving on.</p><h4>RESTful Principles:</h4><p>REST comes with a common set of conventions and principles in order to architect powerful, flexible, and scalable APIs. For example, one common convention with REST is that when handling a URL’s method (GET, PUT, POST, DELETE, etc), we use <em>nouns</em> instead of <em>verbs </em>for the resource name. This means that <a href="http://www.example.com/getusers">www.example.com/<strong>getusers</strong></a> would be <a href="http://www.example.com/users,">www.example.com/<strong>users</strong>,</a> and that will <strong>GET</strong> the <strong>users</strong> resource. Here are some more:</p><ol><li><strong>Client-server architecture</strong>: this is to help separate concerns, as managing state between a client and server would become exhausting, not only for a programmer, but exhausting on the system as a whole. In the example above, the Ruby API was the server, and there was a Go client.</li><li><strong>Communication should be stateless</strong>: the interaction between the client and the server should be without state, meaning each request from the client to the server is a self-contained interaction, that does not require context from previous requests. However, both the client and server can hold their own state.</li><li><strong>Cache-able</strong>: being able to cache a response from a server can greatly speed up interactions, in some cases, completely eliminating them.</li><li><strong>Uniform interfaces between components</strong>: this is a distinguishing feature of REST, where the independent evolution of components is encouraged. This is because the actual implementation of the components (the code) and the services (what that code provides) are decoupled. In the Ruby and Go example, the two components were the Ruby RESTful API and the Go client, whereby the implementation of the Ruby code is unimportant to the Go client, <em>as long as</em> the Go client receives the Media Type it expected to receive, among others.</li></ol><h4>REST Interface Constraints:</h4><p>Okay, so we now know some of the core principles behind what makes RESTful APIs RESTful, but what constraints do we need to implement on our RESTful APIs? Here are the main four:</p><ol><li><strong>Identification of Resources</strong>: One of REST’s key abstractions is a resource. These are identified in requests, such as <a href="http://www.example.com/Users">www.example.com/users</a>, where the resource in this case is <strong>users</strong>. This is conceptually separate from representation of the response, which could be a Media Type specified by <strong>text/html</strong> or <strong>application/json</strong>, for example. More explanation in #2.</li><li><strong>Manipulation of Resources Through Representations</strong>: A representation can indicate the current or desired state of a requested resource, as well as other forms such as error conditions for a response. The data format of a representation is known as a <em>media type,</em> as explained above in the glossary section. If a client holds a representation of a resource, such as a representation of all the <strong>users</strong>, it has enough information to modify or delete this resource. So, if a request for the resource <strong>users</strong> is sent from our Go client to the Ruby API, a <em>representation</em> of that resource could be the response. Once the Go client has a representation of that resource, it might execute a DELETE request on all the <strong>users</strong>, or a single user resource if it has the authorization to do so.<strong> Be careful not to confuse a resource from it’s representation</strong>. Think of it as a box filled with old toys you had as a kid: The box has a name written on it, “old toys,” and inside the box is the representation (the toys) of that resource (the “old toys” box). This isn’t entirely accurate, but hopefully it helps paint an image in your head.</li><li><strong>Self-Descriptive Messages</strong>: A message should contain enough information to describe how to process it. For example, if the response to a GET request is JSON, the Media Type should be specified as <strong>application/json</strong> in order for the response to be properly processed. There are a few things going on here. In the GET request, the request specifies that the HTTP method is GET, and the Media Type is <strong>application/json</strong>. So, inside this message, it’s self-descriptive because it specifies <em>what to do with the data it’s requesting</em>. This is why the message is also referred to as stateless or context-free; the message requires nothing outside the scope of itself to be processed.</li><li><strong>Hypermedia as the Engine of Application State (HATEOAS)</strong>: This is a fancy way of stating that what actions are available to the client vary as the state of the resource varies. In RESTful APIs, we use Hypermedia as the way we move state around. Hypermedia often is a link to another resource, however it can also be audio, video, graphics, or plain text. As described in this <a href="http://exyus.com/articles/rest-the-short-version/">article</a>, “a RESTful application enables the server to inform the client of the possible ways to <em>change the state of the application via hypermedia.”</em> To use the Twitter example again, say a user navigates to twitter.com. The user has two options: log in or create an account. These are both controlled by hypermedia links, which are used as the <em>engine</em> of application state. Say the user doesn’t have an account. They fill in their details, and hit “Submit.” A POST request is sent by their browser to the server, which then changes the application state of Twitter (to one where the user is now logged in). <em>This</em> is an example of using HATEOAS.</li></ol><p>To sum up some of the concepts of REST covered so far, here’s what <a href="https://twitter.com/rgsimon">Raphael Simon</a>, one of creators of <a href="http://goa.design/">goa</a> had to say about REST:</p><blockquote>REST services expose state through resources (state can be data in a database for example). Each resource represents an abstraction that usually maps to a model in the backend (a “customer”, a “product”, etc). It doesn’t have to be a one to one though, for example relationships may be exposed as resources as well or may be hidden from the API depending on what the service needs enabled. Resources are managed by making requests to the service that exposes them. In HTTP REST establishes the following mapping:<br>* POST to the collection of resources to create a new resource<br>* PUT/PATCH to an element in the collection to update it. “Usually” PUT is used for full updates while PATCH is used for partial updates.<br>* GET to the collection returns all resources<br>* GET to an element of the collection returns that element<br>* DELETE to an element of the collection deletes that element</blockquote><blockquote>From a strict REST point of view, this is pretty much it. In reality APIs tend to expose additional actions on resources. REST dictates that these should be represented as resources. For example if a service exposes a “vehicle” resource and the intent is to allow the API user to start the vehicle, REST would dictate that a “started_vehicle” resource be introduced for example. Creating that resource would return a started vehicle. Sometimes though that is unpractical (typically actions that tend to update state like the example here). In these cases resources define additional actions typically located under the resource location.</blockquote><h4>To Sum Up What We’ve Covered…</h4><p>I covered <em>a lot</em> of content in this post, so feel free to go back, read it (or parts of it) again. It’s okay to not fully understand what’s going on yet. However, what we’ve covered so far is this:</p><ol><li>Application Programming Interfaces (APIs) are like User Interfaces (UI) but for programmers. They should be designed to be easy to use and discover, much like UIs.</li><li>REST stands for REpresentational State Transfer. It was initially proposed by Roy Fielding, and provides a set of conventions that standardizes the creation of uniform interfaces in APIs.</li><li>REST is based on a client-server architecture, is stateless, and is preferably cache-able. Most often it is implemented via HTTP as to use HTTP’s methods for CRUD operations.</li><li>REST’s API constraints include the identification of resources, the manipulation of resources through representations, should have self-descriptive messages, and Hypermedia is the Engine of Application State, meaning that the actions that are available to the client is based off the state of that resource.</li></ol><h4>What’s Next?</h4><p>Next up we’re going to take a look at some main considerations that go into designing a RESTful API, building off of our current working knowledge so far. Then, in the third and last article, we’ll put it all together by implementing that design in code.</p><p>Stay tuned for more in the coming weeks!</p><p><strong>Sources:</strong></p><ul><li><a href="http://www.restapitutorial.com/lessons/whatisrest.html">REST API Tutorial</a></li><li><a href="http://racksburg.com/choosing-an-http-status-code/">Choose an HTTP Status Code</a></li><li><a href="https://github.com/Mashape/apiglossary">API Glossary</a></li><li><a href="https://betimdrenica.wordpress.com/2015/03/09/ideal-rest-api-design/">Ideal REST API Design</a></li><li><a href="https://github.com/Kikobeats/awesome-api">Awesome API</a></li><li><a href="http://jsonapi.org/">JSON API</a></li><li><a href="https://tools.ietf.org/html/draft-kelly-json-hal-07#ref-I-D.wilde-profile-link">JSON HAL</a></li><li><a href="http://sookocheff.com/post/api/on-choosing-a-hypermedia-format/">On Choosing a Hypermedia Type for your API</a></li><li><a href="http://sookocheff.com/post/api/how-rest-constraints-affect-api-design/">How REST Constraints Affect API Design</a></li><li><a href="http://exyus.com/articles/rest-the-short-version/">REST - The Short Version</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e26f0978616" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/objects-at-rest-part-1-what-is-it-3e26f0978616">Objects at REST, Part 1: What Is It?</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional Workflows in Postman]]></title>
            <link>https://medium.com/the-restful-web/conditional-workflows-in-postman-f79c05306671?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/f79c05306671</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[postman]]></category>
            <dc:creator><![CDATA[Ankit Sobti]]></dc:creator>
            <pubDate>Tue, 22 Mar 2016 23:03:26 GMT</pubDate>
            <atom:updated>2016-03-22T23:58:24.111Z</atom:updated>
            <content:encoded><![CDATA[<p>There are some products available in the market to create and execute API workflows. However, most of them are limited by their linear, non-reactive execution. We knew we could create something much more effective and decided to add workflow support to Postman. Postman 4.0, in conjunction with <a href="https://www.npmjs.org/package/newman">Newman</a>, the command line companion, is now powerful enough to help you create and execute <a href="https://www.getpostman.com/docs/workflows">non-linear workflows in your Collections</a>!</p><p>This latest release builds upon our existing <a href="https://www.getpostman.com/docs/running_collections-1">Collection Runner</a>. It introduces a new function called <strong>postman.setNextRequest</strong>. As is evident from the name, you just need to specify the name of the subsequent request and the runner will take care of the rest. It has the following signature:</p><blockquote>postman.setNextRequest(“Request Name”);</blockquote><p>Let’s go over an example workflow so you can get a sense of how this works.</p><p>You might have met Postman’s <a href="https://www.getpostman.com/about-us">Chief Happiness Officer</a> earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRoWIELn1ZidMI-grxKsVQ.jpeg" /></figure><p>This is Cooper. He’s one year old and eats three meals a day. He’s allowed to eat only six pre-approved food items. We store them in a database. Cooper is very picky. You can’t repeat an item on the same day unless you want to risk a tantrum. So I want to generate a random meal plan for him at the beginning of the week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*486RglVX9kPEfrSv2UOeug.png" /></figure><p><strong>The workflow:</strong></p><p>First makes the API call to GET the list of approved food for Cooper from the database.</p><p>Then it creates an entry for each day, 3 times a day, 7 days a week</p><p>All 3 meals in a single day have to be unique.</p><p>If the API call fails, poor Cooper goes hungry 😟</p><p>You can check out the documentation for the collection <a href="https://documenter.getpostman.com/view/583/coopers-meal-plan/4u2">here</a> and download the collection <a href="https://app.getpostman.com/run-collection/9be37cbbd4169d08573f#?env%5BCooper-Remote%5D=W3siZW5hYmxlZCI6dHJ1ZSwia2V5IjoidXJsIiwidHlwZSI6InRleHQiLCJ2YWx1ZSI6Imh0dHA6Ly8xNTkuMjAzLjIzMy4yMzc6MTMzNyJ9XQ==">here</a>:</p><p>In case you’re curious, I ran the collection and here’s what Cooper’s eating this week!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*Alhn3IUJDYwqfc4haVlteg.png" /></figure><p>In general, the postman.setNextRequest parameter is associated with the request and can be set in the pre-request or the test script. In case of more than one assignment, the last set value is considered. If postman.setNextRequest is absent, the runner defaults to the linear execution and moves to the next request. postman.setNextRequest(null) terminates execution.</p><p>I hope you find this useful. <strong>postman.setNextRequest</strong> is just the beginning and we will push out more APIs to easily create complex workflows in the coming quarters within Postman. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f79c05306671" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/conditional-workflows-in-postman-f79c05306671">Conditional Workflows in Postman</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first experience creating an API]]></title>
            <link>https://medium.com/the-restful-web/making-my-first-api-using-python-flask-8d7d83e45e36?source=rss----b0d9bf327991---4</link>
            <guid isPermaLink="false">https://medium.com/p/8d7d83e45e36</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Christina Ng]]></dc:creator>
            <pubDate>Tue, 22 Mar 2016 03:44:46 GMT</pubDate>
            <atom:updated>2015-04-16T05:03:56.668Z</atom:updated>
            <content:encoded><![CDATA[<h4>A weekend side project to build a Home Automation API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*3UaLDKs6bJRMtYoPDCIWBw.png" /></figure><p>Earlier this year I joined <a href="https://www.mashape.com/">Mashape</a>, an API platform and marketplace allowing you to distribute, monitor, and manage your APIs. While I was familiar with what an API was, I had never made one myself. I learnt programming when I was in college, and had some experience with Python at work (mainly scripting). Over the past couple of weekends, I took it as a personal challenge to learn how to create my own API, as well as experience some “real-world” coding. I worked on what I call the “Smarthome API”, an API for home automation that can control the devices in my house, such as the lights, fan, WeMo, door lock, and climate (via Nest).</p><blockquote>In this post, I have documented my journey, the steps I have taken, the learning, and experiences along the way (mostly of my housemates who had to live in darkness while I was testing the app).</blockquote><h4>1. Defining the problem</h4><p>My housemate recently installed several flavors of home automation hardware:</p><ol><li>Z-wave switches and locks that enable home automation over a wireless network. We use <a href="http://getvera.com/"><strong>Vera</strong></a><strong>, </strong>a smart home gateway, to interact with the switches and devices.</li><li>A <a href="https://nest.com/"><strong>Nest</strong></a><strong> </strong>thermostat, of which we use the mobile app to adjust the temperatures and switch between “Home” and “Away” modes.</li><li><a href="http://www.belkin.com/us/Products/home-automation/c/wemo-home-automation/"><strong>Belkin WeMo</strong></a> appliances.</li></ol><p>All these products turned out great when we found ourselves too lazy to get out of bed to turn off the light switch, or check if the door is locked. However, it was rather cumbersome to manage different apps, or to manage every device individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LD6jqEogROIz70JVe2l3UQ.png" /><figcaption>It also helped that the Vera web interface was not the most aesthetically pleasing.</figcaption></figure><p>I wanted to have more flexibility and control over these devices. For a start, I scoped out these basic requirements for my API:</p><ul><li>Be able to retrieve the list of all the switches/ devices (lights, locks, Nest) in the house — GET method</li><li>Be able to retrieve information on each individual switch/ device, e.g. Name, current state, etc — GET method</li><li>Be able to modify the state of each switch/ device, e.g. turn a light on or off — PUT method</li></ul><h4><strong>2. Choosing a language and framework</strong></h4><p>This was easy. Since I was most familiar with Python, I decided to go with <a href="http://flask.pocoo.org/">Flask</a> (a Python micro-framework), because it is lightweight. Of course, there were many other options, but I’ll not be going into details on the pros and cons of each.</p><p><strong>PS. For the rest of this post, I’ll be referring to the switches/ devices as Lights. In reality, they control not just the lights, but also the fan, WeMo, etc. “Lock” refers to the door locks, while “Nest” refers to the climate control.</strong></p><h4><strong>3. Building the scaffolding / creating the models</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*qRJHcwG_bw-UCaJLd0yWUw.png" /><figcaption>Once I had everything set up and managed to get my “Hello World” running, it was time to get my hands dirty.</figcaption></figure><p>I created the model class for a Light object (on hindsight, I probably should have named it “DeviceSwitch” instead) with 4 properties:</p><ul><li>id — device id as specified by Vera</li><li>name — name of the device/ switch to be controlled</li><li>room — name of the room which the device/ switch is located in</li><li>status — 0 for when the device/switch is off, 1 for when it is on</li></ul><p>Next, I created my first endpoint: GET /lights which was supposed to return a JSON with information of all the Lights. I fed it with some dummy data, and saw that my method was working correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*Zh7njCxVvH2jr1NKXfuAXQ.gif" /><figcaption>Pretty much my reaction when I realized that the endpoint was working, albeit with dummy data.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*Ub2SAjKGLexcf_3UZKpIzA.png" /><figcaption>Sample response for GET /lights/1 endpoint</figcaption></figure><p>The second endpoint: GET /lights/&lt;id&gt; involved returning a JSON with properties of the requested light. Once again, the method was verified to work correctly with mock data.</p><p>Changing the state of the Light was slightly more complicated, as the PUT request would need to take in an &lt;application/json&gt; content type with the desired state. For this, I made use of the <a href="http://www.getpostman.com/">Postman Chrome App</a> which was able to verify that my method was working correctly. Success!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*UyhMqk69pgVFEtHVdZ-cVg.gif" /></figure><blockquote>At this point, I pretty much went around the house and showed off my wonderful “working” API to my housemates, although it didn’t exactly do anything. They were not impressed ☹</blockquote><h4>4. Figuring out the Vera interface</h4><p>The difficult part came when I had to figure out how to make requests to Vera to actually control the hardware. I opened the Vera control panel and used Chrome’s inspector to filter the data packets that were sent and received while turning lights on and off.</p><p>For a start, I figured out the request URL which Vera uses to retrieve all the devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49mbZFD9-7BwZFfa6iGq7Q.png" /><figcaption>HTTP Request and response for retrieving information about Vera devices</figcaption></figure><p>It turned out that the request URL followed a simple pattern, and the I could request device information with just two lines of code:</p><pre>p = {‘rand’: random.random()}<br>response = requests.get(“http://192.168.1.88/port_3480/data_request?id=user_data&quot;, params = p)</pre><p>I used the same method to figure out the requests that I needed to make to Vera in order to change the state of a Light switch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HgiuyS_WY_mV3NyrJGDQRw.png" /><figcaption>HTTP Request and response for modifying the state of a Vera Light switch</figcaption></figure><p>All that was required was the id of the device, the target state to change to, as well as a random number parameter.</p><pre>p = {‘DeviceNum’: id, ‘newTargetValue’: <em>&lt;the new state&gt;</em>, ‘rand’: random.random() }<br>response = requests.get(“http://192.168.1.88/port_3480/data_request?id=lu_action&amp;output_format=json&amp;serviceId=urn:upnp-org:serviceId:SwitchPower1&amp;action=SetTarget&quot;, params = p)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*AgGXmUzU_8kfqcR-mOPrPQ.jpeg" /></figure><p>On hindsight, this was much easier to explain, but it took me some effort to learn and understand exactly what I was doing then.</p><h4>5. Making it work</h4><p>Since I had figured out how the HTTP requests worked, all that was left was making my API perform the desired action and return the correct response. (Yes, my API was still not really “working” after all the work ☹)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*xYLzqIu_l8owG7FVzinUJQ.jpeg" /></figure><p>To list the lights in my home, I inspected the JSON response from the HTTP request, retrieving the values of id, name, room, and state of the device. I parsed the variables into a newly created Light object. Iterating through the entire response, I was able to build a list of Light objects which were then returned by the GET /lights method as a JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*tCOTrDA7ALGqpszznV5GxA.png" /><figcaption>Multiple loops and nested if-s which were not very pretty, but it got the job done.</figcaption></figure><p>To switch the state of a light, I decided to have my API accept a PUT request with the id in the URL parameters and the requested state in the JSON body. Implementing this was a 2 step process:</p><ol><li>Verifying the legitimacy of the JSON request</li><li>Performing the actual request to Vera and returning a legit response</li></ol><p>For a start, I only verified that the JSON request defined a proper state which could be used to control the Light device. If the state was specified, I’d send the request to switch the state. If there was no error, the method would return an OK response. Otherwise, it <em>should</em> return the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*DoEZqoJsI_Yyhvnyrfq0Jw.png" /><figcaption>Once again, very messy and ugly code, but it works, so we’ll leave the refactoring to later.</figcaption></figure><blockquote>Although my code was somewhat messy and ugly, it worked. And I made sure everyone in the house knew it by randomly switching on and off the lights in their room ;)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*k0TdoZafsQuJtPmRICqEvA.jpeg" /></figure><h4>6. Doing the same thing for other devices</h4><p>Once the three methods worked for Lights, it was easy to replicate them for the Locks. Most of the code was pretty straightforward and looked pretty much the same, except for some minor URL changes in the Vera HTTP request. However, I did enforce that a password needed to be parsed in the JSON request when changing the status of the lock. (I definitely didn’t want random hackers being able to remotely lock and unlock my front door!)</p><h4>7. Refactoring the code</h4><p>Getting to this point was a proud moment for me. However, my code was messy and ugly, with inconsistent variable names, multiple nested loops and conditions, and a ton of duplicated code. One key issue was that my JSON response was returning the room id instead of the actual room name. I needed to retrieve the room names from the Vera API once again, and return them in my response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*YeysYJgD8VH3SAwWdklYXA.png" /><figcaption>Sample response body of GET /lights endpoint returning room ID instead of room name</figcaption></figure><h4>8. Adding verification functions and increasing sleep time</h4><p>At this point my API worked for switching individual devices on and off. I tried to create an endpoint that would turn all the lights off. However, I found that not all the lights were being turned off! Upon investigation, I realized that all my requests to the Vera API was succeeding and returning an OK response even though not all the lights were turning off in reality ☹</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*POAopGPj9jvoxlurljg1fQ.jpeg" /></figure><blockquote>While I grappled with the issue, my unfortunate housemates had to suffer in darkness, since I refused to switch on the lights for them until I fixed the bug.</blockquote><p>To resolve the issue, I decided to add a verification function to ensure that the device state switch was successful. Otherwise, I would send the request again. I also added a sleep time just in case the updated device state was not reflected soon enough in the API response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*5eO_kEjZYoPizAN1Xl4bxw.png" /><figcaption>Verification function to ensure that the device was switched to the target state</figcaption></figure><h4>9. Adding Nest and creating a Devices superclass</h4><p>It was time for me to add the Nest device into the mix. For the sake of simplicity, I chose to control Nest through the Vera API, instead of the native API which was recently released. The Nest object that I created was pretty similar to the existing Light and Lock objects. Hence, I decided to create a Devices superclass, in which the Lights, Locks, and Nests would inherit from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*M3MmIZqydME_v21xl_bORA.png" /><figcaption>The Vera API considers the Nest controller as two different devices.</figcaption></figure><p>The Nest device was slightly more complicated, as the Vera API accounted for each Nest controller with a different id — one id for the Nest device controlling the temperature range, and another to switch between the states. I chose to expose only the id of the main Nest object controlling the temperature, and stored the other controller id as a variable within the main object class.</p><p>Upon creation of the Devices super class, I moved the update &amp; verify state functions (functions controlling the PUT endpoints) into the class definition. This way, I had cleaner and prettier code with less repetition.</p><h4>10. In comes Redis, Custom JSON Encoder, and Device Decoder</h4><p>I had created endpoints to turn all the lights on and all the lights off (which I called the home and away modes). I added in the “features” to lock doors and turn the A/C down to the away mode (and a corresponding set of states for the home mode).</p><p>But manually hard coding the “Home” and “Away” modes for all the devices was not very efficient. I wanted to provide a more extensible solution for creating custom modes, where the API users would be able to store and reset the house to previous modes.</p><p>To do this, I needed to store the current states of all the devices (Lights, Locks, Nests), and be able to retrieve them when necessary. I needed some form of persistent storage… and this was when Redis came into the picture.</p><p>To store a mode, I created a new PUT method for /states/&lt;name of slot&gt; which stored the state of all the devices in Redis. To do that, I wrote a custom JSON Encoder which included a special “_type” variable in each representation of object to determine if it was a Light, Lock or Nest object. This was necessary as I needed to recreate the object based on its type during decoding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*U6wt6b0mjuBloBdD4uSMwA.png" /><figcaption>Custom JSON Encoder which added a “_type” variable and custom Device Decoder which recreated the objects based on their “_type” variable</figcaption></figure><p>Once I was able to deserialize the JSON that was stored in Redis, creating the PUT method for loading a saved state was as simple as iterating through the states, and calling the respective class function to switch the state of each device. All these was done with lots of code refactoring, of course ;)</p><h3>Future plans?</h3><p>So there, over a couple of weekends, I managed to create my first API to make my house a smarter home. There are definitely areas of improvements, for example:</p><ul><li>Using ORM for creating models instead of writing custom models</li><li>Some kind of parallelism to set the state of the devices, locks, and Nest all at the same time instead of sequentially. This will greatly speed up the response of the API.</li><li>Verify the state of all devices at once instead of verifying them individually as their states switch. This will also reduce the number of requests being sent to Vera.</li><li>Ability to roll back to the original state if there is an error in switching the state of the device — This will involve saving the original state before a change is made, and then rolling it back if an error occurs.</li></ul><p>While some of these changes can be made pretty quickly, I’m calling this done for now as I work on my next project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*tksPodGl1WuhJd5tvAt5dw.gif" /></figure><h3>What’s happening to the API?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZlAtQj2hVBSV2Czp1PD9Q.png" /></figure><p>This project doesn’t end here! Now that I&#39;ve got the API ready, my housemate, <a href="https://medium.com/@benedictchan">Ben</a>, is in charge of the front-end work of creating an Android app using my API.</p><p>For now, this is what the app looks like — it is very basic and lacking in design, but does exactly what we need from one place, and it’s still a work in progress.</p><blockquote>I also heard that he had hacked up a bitcoin integration where sending money to him would result in the door opening ;)</blockquote><p>I hope to update this with more screenshots once the app is completed! ☺</p><p>Update (2/15/2015): Omg! Someone <a href="https://github.com/christinang89/smarthome/pull/1">made a pull request</a> to my repo and cleaned up the mess! ☺</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ceBQfbPPzkEAWVnZDNNEBQ.png" /></figure><p>Update (4/15/2015): About 6 months ago, I bought an iPhone after being an avid Android user for the past 6 years (yes, I owned the G1!). The first thing I missed in iOS was, of course, my wonderful smarthome app. I decided to take the chance to learn some iOS programming by porting the app over to iOS, and here’s what the app looks like. <a href="https://github.com/christinang89/Unicorn">The code isn’t the prettiest</a>, but hey, it works! ;)</p><h3>Acknowledgments</h3><p>All this would not have been possible without the patient guidance of <a href="http://www.linkedin.com/in/bencxr">Ben</a> who taught me everything I needed to know to get this far. The github repo for the API is here: <a href="https://github.com/christinang89/smarthome">https://github.com/christinang89/smarthome</a>, although it currently only works for my house. The repo for the Android app is available at <a href="https://github.com/bencxr/kotl">https://github.com/bencxr/kotl</a>, and for the iOS app: <a href="https://github.com/christinang89/Unicorn">https://github.com/christinang89/Unicorn</a></p><p>This has been fun side project. While I set out expecting to learn about creating APIs, I ended up taking away a lot more. I learnt how to sniff data packets. I learnt how to write actual code outside of a programming assignment context. I learnt about Redis/ persistent storage, and custom serializers and deserializers. I learnt many design patterns in developing a web application, some coding best practices, <a href="http://legacy.python.org/dev/peps/pep-0008/">PEP 8</a> (Sorry, I know my code isn’t exactly conforming to it), and how to solve a large problem in simple, manageable pieces.</p><blockquote>So I would say, if you’re learning how to code, learn how to make an API! ☺</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*UXskVuaaVGlQmkxw0YX2Zg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d7d83e45e36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-restful-web/making-my-first-api-using-python-flask-8d7d83e45e36">My first experience creating an API</a> was originally published in <a href="https://medium.com/the-restful-web">The RESTful Web</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>