Designing a RESTful API with Python and Flask

In recent years REST (REpresentational State Transfer) has emerged as the standard architectural design for web services and web APIs.

if you are new to Flask please go to Flask Docs and get basic concept of flask.  let’s dive in to coding part. I am going to explain very basic example of designing RESTful API with Flask.    let’s start with hello world application.

#!flask/bin/python
from flask import Flask

app = Flask(__name__)

@app.route('/')

def index():
return "Hello, World!"

if __name__ == '__main__':
app.run(port=5662, debug=True)

now you need to run this hello world application.

python helloworld.py

above command used to run python application.

okkY , now lets go ahead..

next, i gonna explain you how to create RESTful Web application.

Before creating Dynamic Web Application with Flask, you must need to understand the directory structure of flask.

/templates :  you must need to put all your template files (.html) inside this folder

/static: you can put all your static files usually JavaScript and CSS files

you need to use this syntax to include css or js files from static folder.

url_for('static', filename='style.css')

lets go for very basic web app

#!flask/bin/python
from flask import Flask, render_template
#from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('main.html')

if __name__ == '__main__':
       app.run(port=5662, debug=True)

you need to put main.html file inside templates folder as mentioned above.

main.html file contain simple hello world. that you can do it urself.

=== now lets create dynamic application which return JSON data to front end html file and i will show you how to send ajax request to REST API. ===

This application provides facility to make addition of two numbers. so html file contain two inputs and while submitting form using JQuery it will request to Rest API (_add_numbers)

Python Code:

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/_add_numbers')
def add_numbers():
"""Add two numbers server side, ridiculous but well..."""
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)

if __name__ == '__main__':
app.run(port=5662, debug=True)

HTML Code

create layout.html

<!doctype html>
<title>jQuery Example</title>
<script type=text/javascript
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type=text/javascript>
var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
{% block body %}{% endblock %}

create index.html

{% extends "layout.html" %}
{% block body %}
<script type=text/javascript>
$(function() {
var submit_form = function(e) {
$.getJSON($SCRIPT_ROOT + '/_add_numbers', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$('#result').text(data.result);
$('input[name=a]').focus().select();
});
return false;
};
$('a#calculate').bind('click', submit_form);
$('input[type=text]').bind('keydown', function(e) {
if (e.keyCode == 13) {
submit_form(e);
}
});
$('input[name=a]').focus();
});
</script>
<h1>jQuery Example</h1>
<p>
<input type=text size=5 name=a> +
<input type=text size=5 name=b> =
<span id=result>?</span>
<p><a href=# id=calculate>calculate server side</a>
{% endblock %}

 

————————————————————————————————-

hope you all like this .. congrats now you can develop beautiful RESTful Dynamic Application on Flask.  🙂

Advertisements