API in Flask - REST API in Python
APIs
APIs are something awesome.I personally love to talk about it.API are nothing but a piece of code which eases the software development process.On this you may think how this happens.So if you lool at our website we have also use many APIs such as the Chat System , Push Notification - What are these - These are nothing but the examples of API.If you still are not able to grab it , So for you I am going to narrate a story to you:
You might have heared about third party applications like goibibo and makemytrip both are Flight Booking's site.Suppose when you search for a flight between City A to City B you are presented with many results from different airlines.So how this happens.Does goibibo or makemytrip has the permission to access the databases of indigo or air india.The answer is absolutely no.As no such reputed company would take a risk of giving the access to it's databases to such third paries.So again the question arises how these sites gets the results of flights arrival and departure do they make this by their own.Seriously talking it can't happen they actually uses the APIs generated or created by Indigo or Air India to access the information without having the control on there databases.Below I have put an image that will help you to understand the use of APIs.
Building REST API in Flask
REST APIs are nothing but a type or classification of API.REST means REpresentational State Transfer.In flask we have to install a package called flask-restful to start developing REST APIs.
But wait you can also build REST APIs without using any third party packages.So first of all we will try to make the REST API using Flask only.
EXAMPLE
from flask import Flask, jsonify, request
# creating a Flask app
app = Flask(__name__)
@app.route('/', methods = ['GET', 'POST'])
def home():
if(request.method == 'GET'):
data = "I am a REST API"
return jsonify({'data': data})
@app.route('/home/<int:num>', methods = ['GET'])
def square(num):
return jsonify({'data': num**num})
# driver function
if __name__ == '__main__':
app.run()
No comments: