<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Henrique Dantas on Medium]]></title>
        <description><![CDATA[Stories by Henrique Dantas on Medium]]></description>
        <link>https://medium.com/@hdantas?source=rss-b769bf7ac9f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PG_gfNX4yCdKGipgzV4V9g.jpeg</url>
            <title>Stories by Henrique Dantas on Medium</title>
            <link>https://medium.com/@hdantas?source=rss-b769bf7ac9f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:24:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hdantas/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Writing an API with Flask-RESTful (Part 2)]]></title>
            <link>https://medium.com/@hdantas/writing-an-api-with-flask-restful-part-2-93a0dfcd54a7?source=rss-b769bf7ac9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/93a0dfcd54a7</guid>
            <category><![CDATA[rest-secured]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Henrique Dantas]]></dc:creator>
            <pubDate>Tue, 19 Jul 2016 12:56:49 GMT</pubDate>
            <atom:updated>2016-07-27T14:52:51.224Z</atom:updated>
            <content:encoded><![CDATA[<p>On <a href="https://medium.com/@hdantas/writing-an-api-with-flask-restful-part-1-61b0e26e0e5b">Part 1</a> of this post we’ve described what an API is, what server code is needed to handle it, and finally how to apply it for a simple API in Flask as well as Flask-Restful. Just like for Part 1, all code that will be show is readily available on <a href="https://github.com/hdantas/pokemonapi-tutorial/">this repository</a>.</p><p>The current part builds on top of that and explores The Pokémon API v2 which will allows us to explore three common use cases: CRUD application with optional query strings and complex body schemas, nested input objects and custom validation.</p><h4>Pokémon API v2</h4><p>To showcase what is possible with Flask-RESTful let’s consider <a href="https://gist.github.com/hdantas/e4e15e24421c6227d754c4a25f646195">v2 of the Pokémon API</a> which has more complex Pokémon representations and supports 2 additional HTTP methods: PUT and DELETE.</p><p>In addition to number and name, Pokémons now consist of type, weaknesses and evolutions. The fields type and weaknesses are both lists of strings. The evolution field is a list of simplified Pokémon objects (only contain name and number, since all evolutions share type and weaknesses). This is what the updated version of the Pokédex looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0b86d20d070694b0a406e9771736159/href">https://medium.com/media/c0b86d20d070694b0a406e9771736159/href</a></iframe><p>This new version of the Pokémon object is reflected in the Pokémon API v2 documentation which you can find on <a href="https://gist.github.com/hdantas/e4e15e24421c6227d754c4a25f646195">GitHub</a>. Furthermore, it is now possible to update and delete existing Pokémons, respectively with the PUT and DELETE HTTP methods. Finally, the GET method now supports a query string which allows the user to retrieve a single Pokémon from the Pokédex.</p><p>The new implementation is more complex and therefore will be broken down in 4 parts, one for each HTTP method.</p><h4>GET</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e81ba03f640a9436ee02eb4308107476/href">https://medium.com/media/e81ba03f640a9436ee02eb4308107476/href</a></iframe><p>The implementation is not too different than in Part 1. In order to support the optional argument, the <em>add_argument</em> function now contains the <em>required</em> argument set as False. And some logic was added to ensure the query parameter number exists and corresponds to an existing Pokémon.</p><h4>POST and PUT</h4><p>POST and PUT have similar parser implementations since they both expect a valid Pokémon object to be included in the body of the HTTP request. Therefore we’ve created a function for it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c7554849cb741c6ddf0286d0f372dc7/href">https://medium.com/media/3c7554849cb741c6ddf0286d0f372dc7/href</a></iframe><p>There are two major changes to highlight. The first one is the creation of a custom type: <em>list_of_strings</em>. The new type is defined as a function that validates if the argument is, not surprisingly, a list and made up of strings. Both type and weaknesses are of this type.</p><p>The second one is due to the existence of nested types. In order to validate the outer and inner objects it is necessary to create a new parser. After ensuring evolutions is a list in the <em>root_parser</em> we go through each item in that list and perform subsequent validations. In order to look in the right place, we create a new Namespace populated with the current list item and use it as a the request against which the validations are run.</p><p>With the parsing completed, PUT and POST are straightforward to implement. PUT allows the user to modify existing Pokémons while POST supports the creation of new Pokémons that were not previously registered in the Pokédex.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5af562d596c9d1d9d7fab5881b5ae22f/href">https://medium.com/media/5af562d596c9d1d9d7fab5881b5ae22f/href</a></iframe><h4>DELETE</h4><p>Finally, to delete a Pokémon the user must specify the number of the creature and the server replies with a JSON object informing whether the operation was successful or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8c2ad98bfa4cf046d3c7c6ffc2a2ce8/href">https://medium.com/media/d8c2ad98bfa4cf046d3c7c6ffc2a2ce8/href</a></iframe><h4>What next …</h4><p>The official Flask-RESTful <a href="https://flask-restful.readthedocs.io/en/latest/quickstart.html">Quickstart</a> can get you a long way in implementing APIs but it is not so easy to figure out how to support more complex logic. The goal of this article is to shed some light on that and hopefully help some readers along the way. For further reference information check out the <a href="https://flask-restful.readthedocs.io/en/latest/index.html">official documentation</a>.</p><p>Validating all input fields properly to ensure you’re not vulnerable to attacks is the core of what we do at <a href="https://www.restsecured.xyz/?ref=med-flask2">Rest Secured.</a> Flask-RESTful can be a great help in doing just that.</p><p>If you want to test the API you’ve just written for vulnerabilities or already have one up and running, I invite you to ran an automated scan in our website <a href="http://www.restsecured.xyz/">for free</a>. Writing secure APIs that are resistant to malicious input is tough, and testing is the best (only?) way to ensure you’re doing it properly.</p><h3>Conclusion</h3><p>Flask is a popular web framework for Python and even though it was not designed primarily to implement APIs it can do the job fairly well, in particular, when combined with Flask-RESTful.</p><p>Flask-RESTful is a deceptively simple extension but can be used to implement virtually any type of RESTful API and is readily extendable to suit different needs. Navigating the docs is now always easy but hopefully this article can help you in that journey.</p><p>Hope you enjoyed both these articles! Feel free to get in touch if you have any questions or remarks. You can always find me on twitter at <a href="https://twitter.com/intent/user?screen_name=hndantas">@hndantas</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93a0dfcd54a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing an API with Flask-RESTful (Part 1)]]></title>
            <link>https://medium.com/@hdantas/writing-an-api-with-flask-restful-part-1-61b0e26e0e5b?source=rss-b769bf7ac9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/61b0e26e0e5b</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rest-secured]]></category>
            <category><![CDATA[pokemon]]></category>
            <dc:creator><![CDATA[Henrique Dantas]]></dc:creator>
            <pubDate>Tue, 19 Jul 2016 12:52:12 GMT</pubDate>
            <atom:updated>2016-07-27T14:50:03.228Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will go over the details of how to create a RESTful API with <a href="http://flask.pocoo.org/">Flask</a> and <a href="https://flask-restful.readthedocs.io/en/latest/index.html">Flask-RESTful</a>. In Part 1 we will go over the API basics and how to implement a simple API. In <a href="https://medium.com/@hdantas/writing-an-api-with-flask-restful-part-2-93a0dfcd54a7">Part 2</a> we will expand into advanced use cases powered by Flask-RESTful. All code that will be show is readily available on <a href="https://github.com/hdantas/pokemonapi-tutorial/">this repository</a>.</p><p><em>Side note: the original definition and the popular definition of what constitutes a RESTful API </em><a href="https://danpalmer.me/blog/your-api-is-not-restful"><em>often differ</em></a><em>. Depending on where you stand in that discussion, you may or may not consider these APIs RESTful.</em></p><p>Here at <a href="https://www.restsecured.xyz/?ref=med-flask1">Rest Secured</a>, we find security vulnerabilities in APIs for a living so we know how important and difficult it is to write secure code. We are currently working on the 1st version of our API which will allow users to interact with all our services through the API and took this opportunity to share our experience.</p><h3><strong>API Requests</strong></h3><p>Before delving into the details of the implementation we first need to understand how an API call looks like. Let’s consider the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7fae148ff0ab130d4ac665f170c4849/href">https://medium.com/media/e7fae148ff0ab130d4ac665f170c4849/href</a></iframe><p>An HTTP request has 3 parts:</p><ol><li>The HTTP method and URL: the HTTP methods (most common are GET, POST, PUT, DELETE) are interpreted as verbs that act on the resources defined by the URL (in this case: <em>/api/v1/pokemon</em>). To handle this request we need to understand what action do for each verb and be able to map each URL to a resource in a internal data structure (<em>e.g.</em> a database). Further information about the resource to modify can be included in a query string or in the payload of the HTTP request, but that doesn’t apply here.</li><li>HTTP Headers: headers are usually used for configuration details, authentication tokens (<em>e.g.</em> API keys), or client information (<em>e.g.</em> user agent). They also contain information on the format of the payload they consume (<em>*/*</em>) and produce (<em>application/json</em>).</li><li>HTTP body: the last line of the request is the body and may contain extra data. In the example show, the body carries information about the new resource to be POSTed (<em>i.e.</em> created). In order to process the body correctly we need to check the headers for the content-type.</li></ol><p>So, how can we implement this with Flask?</p><h3>Flask</h3><p>Flask is a Python micro web framework that allows developers to quickly get websites up and running with a few lines of code. Throughout this article basic knowledge of Flask is assumed so if you’re not familiar with it, have a look at the official <a href="http://flask.pocoo.org/docs/0.11/quickstart/">Quickstart</a>.</p><h4>The Pokémon API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zaty9dpItL2UsDofl3Cj0g.png" /><figcaption>Of course it had to be about Pokémon!</figcaption></figure><p>We will be implementing a simple Pokémon API that allows you to edit your own Pokédex! To start, it will support only two methods GET and POST and a Pokémon is completely defined by its number and name. You can find the documentation for this API on <a href="https://gist.github.com/hdantas/32279490c8c9208ef4bf4ef05d04ae60">GitHub</a>.</p><p>A GET request will retrieve the complete Pokédex, while a POST will add a new Pokémon to it. If the call is successful, the server will return the Pokémon that was just added, otherwise it will return an empty body. Do note that the API will refuse to add Pokémons that are already in the Pokédex.</p><h4>Implementing APIs in Flask</h4><p>The easiest option for simple APIs is to use native Flask primitives together with the popular requests python library.</p><p>The URL (‘<em>/api/v1/pokemon</em>’) can be consumed just like any other URL with the <em>@app.route</em> decorator, the HTTP method and body are accessible through flask primitives and the global variable <em>request</em>. The implementation looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f8da6f2f07b92e86fb7f6efbb909b45/href">https://medium.com/media/4f8da6f2f07b92e86fb7f6efbb909b45/href</a></iframe><p>For simplicity, in the example the Pokédex is a list of dictionaries, instead of a real database. The remainder of the code is fairly simple.</p><p>The first thing we do, is check the HTTP method.</p><p>For GET, we simply return the Pokédex. Flask has a method called <em>jsonify</em> which sets the appropriate value to the content-type header in the request and converts the dictionary into a JSON representation.</p><p>For POST, we need to perform multiple validations. First, we ensure the content-type is set to JSON, then we check if we can actually convert the body from JSON into a Python <em>dict</em>, and finally we check the Pokémon is valid and does not already exist in the Pokédex. If everything checks out, we append it to our list and return it.</p><p>That was quite straightforward to implement but as the API grows in complexity it is easy to see this code becoming very complicated, very quickly! For example, if the Pokémon representation becomes more sophisticated the number of if’s will grow rapidly. In addition, to provide better error messages we need to write much more code than what is shown. But, the worst part is most of the code is boiler plate and will be repeated over and over again. The repetition can be alleviated with functions but this is far from ideal as you API grows.</p><p>On the plus side, by using Flask you don’t have to learn yet another library and don’t have to increase the list of requirements. If you are planning to implement a simple API and would like to learn more about APIs in Flask, Miguel Grinberg has a great <a href="http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask">tutorial</a>.</p><p>All in all, Flask is versatile enough to accommodate APIs but as they grow it becomes cumbersome to maintain them. Flask-RESTful to the rescue!</p><h4><strong>Implementing APIs in Flask-RESTful</strong></h4><p><a href="https://flask-restful.readthedocs.io/en/latest/index.html">Flask-RESTful</a> is a powerful extension for Flask that was designed to help you build complex RESTful APIs. It follows similar design principles to Flask so it is easy to pick up.</p><p>In essence, each URL is considered a resource and is represented in Python as a class that inherits from Resource (a class provided by the library). For each HTTP method supported there should be a corresponding function, such as get(self), post(self), …</p><p>This is how to implement the same functionality as before with Flask-RESTful:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/601220ed85d2bf8f2a8320c9209defe6/href">https://medium.com/media/601220ed85d2bf8f2a8320c9209defe6/href</a></iframe><p>A few changes are worth pointing out.</p><ul><li>The flask_restful library includes an Api function that returns an object used to map resources to endpoints (lines 5 and 6).</li><li>As mentioned previously, for each method supported by the endpoint there is a function with the method name.</li><li>In addition, the library transparently converts Python data representations into JSON, which comes in handy when returning the Pokédex.</li><li>Flask-RESTful supports parsing of arguments via the <em>reqparse</em> library to facilitate validation of the input and provide richer error messages. The parser defined in post() allows us to explicitly define what arguments we are expecting and where to look for them. The validated arguments are then made available as a dictionary.</li></ul><p>In comparison to native Flask, this version is more concise and, most importantly, has a clearer purpose. Therefore maintaining this code is easier as a lot of the validation and formatting code is abstracted.</p><h4><strong>Advanced Flask-RESTful</strong></h4><p>To really show Flask-RESTful shine, we need a more full featured API. To do that, let’s expand our Pokémon API with a more complex representation of the creatures (including type, weaknesses and evolutions) and support for more operations (PUT and DELETE). You can find the documentation for the new API <a href="https://gist.github.com/hdantas/e4e15e24421c6227d754c4a25f646195">here</a>.</p><p>The Pokémon API v2 allows us to explore 3 common use cases:</p><ul><li>Simple CRUD application with optional query strings and complex body schemas</li><li>Nested input objects</li><li>Custom validation</li></ul><p>The advanced implementation is the topic of the second part of this post, which you can find <a href="https://medium.com/@hdantas/writing-an-api-with-flask-restful-part-2-93a0dfcd54a7">here</a>.</p><h3>Conclusion of Part 1</h3><p>Hope you enjoyed the first part of the article! If you did, I recommend you read the <a href="https://medium.com/@hdantas/writing-an-api-with-flask-restful-part-2-93a0dfcd54a7">second part</a> on advanced Flask-RESTFul.</p><p>Fell free to get in touch if you have any questions or remarks. You can also find me on twitter at <a href="https://twitter.com/intent/user?screen_name=hndantas">@hndantas</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61b0e26e0e5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>