Wednesday, October 5, 2016

Building RESTful APIs With Flask: The DIY Approach

REpresentational State Transfer (REST) is a web development architecture design style which refers to logically separating your API resources so as to enable easy access, manipulation and scaling. Reusable components are written in a way so that they can be easily managed via simple and intuitive HTTP requests which can be GET, POST, PUT, PATCH, and DELETE (there can be more, but above are the most commonly used ones).

Despite what it looks like, REST does not command a protocol or a standard. It just sets a software architectural style for writing web applications and APIs, and results in simplification of the interfaces within and outside the application. Web service APIs which are written so as to follow the REST principles, they are called RESTful APIs.

In this three-part tutorial series, I will cover different ways in which RESTful APIs can be created using Flask as a web framework. In the first part, I will cover how to create class-based REST APIs which are more like DIY (Do it yourself), i.e. implementing them all by yourself without using any third-party extensions. In the latter parts of this series, I will cover how to leverage various Flask extensions to build more effective REST APIs in an easier way.

I assume that you have a basic understanding of Flask and environment setup best practices using virtualenv to be followed while developing a Python application.

Installing Dependencies

The following packages need to installed for the application that we'll be developing.

The above commands should install all the required packages that are needed for this application to work.

The Flask Application

For this tutorial, I will create a small application in which I will create a trivial model for Product. Then I will demonstrate how we can write a RESTful API for the same. Below is the structure of the application.

I won't be creating a front-end for this application as RESTful APIs endpoints can be tested directly by making HTTP calls using various other methods.

flask_app/my_app/__init__.py

In the file above, the application has been configured with the initialisation of the extensions and finally creation of the database. The last statement creates a new database at the location provided against SQLALCHEMY_DATABASE_URI if a database does not already exist at that location, otherwise it loads the application with the same database.

flask_app/my_app/catalog/models.py

In the file above, I have created a very trivial model for storing the name and price of a Product. This will create a table in SQLite corresponding to the details provided in the model.

flask_app/my_app/catalog/views.py

The major crux of this tutorial is dealt with in the file above. Flask provides a utility called pluggable views, which allows you to create views in the form of classes instead of normally as functions. Method-based dispatching (MethodView) is an implementation of pluggable views which allows you to write methods corresponding to the HTTP methods in lower case. In the example above, I have written methods get() and post() corresponding to HTTP's GET and POST respectively.

Routing is also implemented in a different manner, in the last few lines of the above file. We can specify the methods that will be supported by any particular rule. Any other HTTP call would be met by Error 405 Method not allowed.

Running the Application

To run the application, execute the script run.py. The contents of this script are:

Now just execute from the command line:

To check if the application works, fire up http://127.0.0.1:5000/ in your browser, and a simple screen with a welcome message should greet you.

Testing the RESTful API

To test this API, we can simply make HTTP calls using any of the many available methods. GET calls can be made directly via the browser. POST calls can be made using a Chrome extension like Postman or from the command line using curl, or we can use Python's requests library to do the job for us. I'll use the requests library here for demonstration purposes.

Let's make a GET call first to assure that we don't have any products created yet. As per RESTful API's design, a get call which looks something like /product/ should list all products. Then I will create a couple of products by making POST calls to /product/ with some data. Then a GET call to /product/ should list all the products created. To fetch a specific product, a GET call to /product/<product id> should do the job. Below is a sample of all the calls that can be made using this example.

Conclusion

In this tutorial, you saw how to create RESTful interfaces all by yourself using Flask's pluggable views utility. This is the most flexible approach while writing REST APIs but involves much more code to be written. 

There are extensions which make life a bit easier and automate the implementation of RESTful APIs to a huge extent. I will be covering these in the next couple of parts of this tutorial series.


by Shalabh Aggarwal via Envato Tuts+ Code

jQuery UI Datepicker with Material Design

A tutorial about jQuery UI datepicker implementation styled as a Google Material Designed widget.


by via jQuery-Plugins.net RSS Feed

Heineken Go Places

Welcome to what we like to call The Interview. Learn about the HEINEKEN Company and about yourself. Do you have what it takes? Learn a craft, learn a trade. There's a journey to be made!
by via Awwwards - Sites of the day

8 Blogger Tools to Help Promote Your Content

ao-blogger-content-promotion-tools-600

Do you want more exposure for your blog? Looking for tools to increase visibility for the content you publish? In this article, you’ll discover eight tools to help you reach a wider audience with your blog content. Step 1: Use External Tools to Promote Your Content If the goal is to drive traffic to your [...]

This post 8 Blogger Tools to Help Promote Your Content first appeared on .
- Your Guide to the Social Media Jungle


by Aaron Orendorff via

Tuesday, October 4, 2016

Saved from Callback Hell

Callback hell is real. Often developers see callbacks as pure evil, even to the point of avoiding them. JavaScriptʼs flexibility does not help at all with this. From the surface, it seems callbacks are the perfect foot gun, so it is best to replace them.

The good news is there are simple steps to get saved from callback hell. I feel eliminating callbacks in your code is like amputating a good leg. A callback function is one of the pillars of JavaScript and one of its good parts. When you replace callbacks, you are often just swapping problems.

A friend tells me callbacks are ugly warts and the reason to study better languages. Well, are callbacks that ugly?

Wielding callbacks in JavaScript has its own set of rewards. There is no reason to avoid JavaScript because callbacks can turn into ugly warts.

Letʼs dive into what sound programming has to offer with callbacks. My preference is to stick to SOLID principles and see where this takes us.

What Is Callback Hell?

I know what you may be thinking, what the hell is a callback and why should I care? In JavaScript, a callback is a function that acts as a delegate. The delegate executes at an arbitrary moment in the future. In JavaScript, the delegation happens when the receiving function calls the callback. The receiving function may do so at any arbitrary point in its execution.

In short, a callback is a function passed in as an argument to another function. There is no immediate execution since the receiving function decides when to call it. The following code sample illustrates:

function receiver(fn) {
  return fn();
}

function callback() {
  return 'foobar';
}

var callbackResponse = receiver(callback); 
// callbackResponse == 'foobar'

If you have ever written an Ajax request, then you have encountered callback functions. Asynchronous code uses this approach since there is no guarantee when the callback will execute.

The problem with callbacks stems from having async code that depends on another callback. I will illustrate the use of setTimeout to simulate async calls with callback functions.

Feel free to follow along, the repo is out on GitHub. Most code snippets will come from there so you can play along.

Behold, the pyramid of doom!

setTimeout(function (name) {
  var catList = name + ',';

  setTimeout(function (name) {
    catList += name + ',';

    setTimeout(function (name) {
      catList += name + ',';

      setTimeout(function (name) {
        catList += name + ',';

        setTimeout(function (name) {
          catList += name;

          console.log(catList);
        }, 1, 'Lion');
      }, 1, 'Snow Leopard');
    }, 1, 'Lynx');
  }, 1, 'Jaguar');
}, 1, 'Panther');

Looking at the above, setTimeout gets a callback function that executes after one millisecond. The last parameter just feeds the callback with data. This is like an Ajax call except the return name parameter would come from the server.

There is a good overview of the setTimeout function on MDN.

I am gathering a list of ferocious cats through asynchronous code. Each callback gives me a single cat name and I append that to the list. What I am attempting to achieve sounds reasonable. But, given the flexibility of JavaScript functions, this is a nightmare.

Continue reading %Saved from Callback Hell%


by Camilo Reyes via SitePoint

How to Promote Your Website Using Just the Right Content

How to Promote Your Website Using Just the Right Content

A decade ago, very few people were exploring the ins and outs of website promotion. Today, there are thousands of courses, books, articles, and other resources that focus on this popular topic. When you promote your website, you’re expecting traffic. Traffic can be transformed into different things such as subscribers and/or sales.

There are now a lot of online marketing strategies that have been developed through the last years. Amongst many traffic generation methods, content marketing is the one that performs the best in terms of organic traffic. SEO for example goes hand in hand with content marketing, because the content you have can make a huge difference in the SERPS positions.

In today’s article we’ll talk about few online promotion strategies that should help understand how to rightly optimize and improve your web business. Let’s begin.

by Guest Author via Digital Information World

Versioning Show, Episode 11, with Vitaly Friedman

In this episode, Tim and David are joined by Vitaly Friedman, founder and Editor-in-Chief of Smashing Magazine. Vitaly takes Tim and David by the hand as they circumnavigate the world of the early web, freelancing, founding an online magazine, amazing free wallpapers, classic failures, editorial guidelines, and the mysterious haunts of foreign writers.

Subscribe on iTunes | Subscribe on Stitcher | View All Episodes

Continue reading %Versioning Show, Episode 11, with Vitaly Friedman%


by M. David Green via SitePoint