Posting JSON data to sinatra with JQuery

I guess this post is mainly useful when you want to build Restful API with Sinatra.   Let’s say you want to pass JSON data to Sinatra backend using JQuery. so you may got very first question is How to parse JSON POST Data in Sinatra rest api ?  am i right ?

so here is full example which demonstrate how to send JSON data to Sinatra REST API.

JQuery Code:

$.ajax({
url: '/test_api',
type: 'POST',
dataType: 'json',
contentType: "application/json",
data:JSON.stringify(data),
success: function(data){
}
})

let’s say data (json variable) contain complex data like

{
"topo": [
    {
      "dpid": "00:00:00:00:00:00:00:03",
      "ports": [
                 3,
                 2
                ]
    }
   ],
"app": "vm_migration"
}

Ruby Sinatra Rest Function

post '/test_api', :provides => :json do
  begin
     # bellow line get post json data
     params = JSON.parse(request.env["rack.input"].read) 
     # you can access key value like bellow
     app = params["app"]
     params["topo"].each do |topo|
            dpid = topo["dpid"]
            # getting each value of key using each
            topo["ports"].each do |port| 
                #Process Data
            end            
        end
  rescue Exception => e
    return e.message
  end
end

Hope it is useful..  plz do comment if it is useful for you..
🙂

any question related to post, feel free to ask.

How to get the facebook details using id?

Hello guys,

Today I gonna explain you how to get Facebook user’s basic detail using user id. bellow function useful when you are developing authentication system of your site using facebook so there you need basic detail of your visitor.

 

function getUserInfo(id)
{
     $.ajax({
	type: "GET",
	url: "https://graph.facebook.com/"+id,
	contentType: "application/json; charset=utf-8",
	dataType: "json",
	success: function(data) {
	   alert(data.name);
	 }
	});
}

That’s it.. isn’t it simple… 🙂

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.  🙂

Dealing with bootstrap alert

hello guys,

I got some problem while dealing with bootstrap alert.

How to show bootstrap alert div again

when we close alert div box, then if again we can’t show that div box. even if we write jquery show() function.

solution:

checkout  <a> tag there you got data-dismiss=”alert” , this will remove div from dom so that’s why we can’t show that div again. so just remove that and bind your function to that div

code:

<a id=”lieclose” onclick=”general_close(this.id)”>×</a>

jquery code:

function general_close(id)
{
	var current_id = "#"+id;
	$(current_id).parent().hide();
}

above function will work for any alert div. just change your id in a tag.

How to redraw bootstrap-error message

$('#loginerrbox').empty();
$('#loginerrbox').append("Please enter valid credentials. 
<a id='crdlogerr' class='close' onclick='general_close(this.id)'>×</a>");					
$('#loginerrbox').show();

above code demonstrate how to redraw new error message on alert div.

hope you like above Tips 🙂