Sunday, May 17, 2020

Building REST APIs with FLASK Python Web Services


Creating Python Webservices with MySql

Beginning with Flask: Flask is a BSD licensed, Python microframework based on Werkzeuge and Jinja2. Flask is a very simple, highly extensible framework. Flask has two major components Werkzeuge and Jinja2 are responsible for providing routing, debugging and web server Gateway Interface(WSGI), Falsk uses Werkzeuge and Jinja2 as a template engine but Flask does not support database access under user authentication or any other high-level utility. Flask is actually a Production-ready framework for developing web applications and services.

Starting Flask: You can install Flask by using the Python Package Index (PPI) and is ready to set up and start developing with and it only takes a few minutes to getting started with Flask.

Installing Flask: With a virtual environment activated, execute the following command to install the latest version of Flask.

$pip install flask
;

This command will install the Flask in your virtual environment. You can use any ide and i am using PyCharm.

Using Virtual Environments: In python 3 the venv module comes pre-shipped as part of the standard library.

To install virtualebv type the following command in your terminal

$ pip install virtualenv


Let me give one simple basic Falsk application example

from flask import Falsk
app = Flask(_name_)

@app.route('/')
def hellow_world():
      return 'Hellow , from Flask'

if _name_ =='_main_':
       app.run()

And this much code is enough to start your first Flask application. So first you have to install Flask library using PIP command.

And will run and open the browser localhost:5000 and print Hellow from Flask.

to run the app type this command in terminal
$ app.py



RESTful Services: REST is a software architectural style for web services that provide a standard for data communication between different kinds of systems. In simple terms, REST is standard for exchanging data over the web for the sake of Interoperability between computer systems. So REStful web services which allow requesting systems to access and manipulate the data using a uniform and predefined set of stateless operations.REST principles are what make is it popular and heavily used.
REST is stateless which simply means that neither the client nor the server has to know the state of each other.
SOAP(Simple Object Access Protocol) is another web service communication protocol which has been overtaken by RST in recent years.SOAP, however, exposes components of application logic as services rather than data.SOAP is a legacy protocol and also lots of other constraints when compares with REST.
SOAP only exchanges data over XML and REST provides the ability to exchange data over a variety of data formats.RESTful services are faster than SOAP.SOAP is preferred when robust security is essential as it provides support for web services security(WS-Security) which is specification security measures are implemented in web services to protect them from external attacks.SOAP is highly extensible with other technologies and protocols like WS_Security, WS-addressing, WS-coordination, and many more.

REST protocol and the following features:

1)Uniform Interface
2)Representations
3)Messages
4)Links between resources
5)Caching
6)Stateless

1) Uniform Interface: it should have a uniform interface to access resources.A logical URI system with Uniform across the system. So it provides a set of methods.

GET - Fetch single or multiple resources and it is safe.
POST- Insert a new resource and it is not safe.
PUT - Insert a new resource or update an existing and it is also not safe.
DELETE - Delete single or multiple resources and it is not safe.
OPTIONS - List allowed operations on a resource and it is safe.
HEAD - return only resource headers and nobody and it is safe.
PATCH - Only update the provided changes to the resource and not safe.

2) Representations: RESTful services focus on resources and providing access to resources. You can think of it as an OBJECT in OOP. here is small example of representations.

1)
<?xml version="1.0" encoding="UTF-8"?>
<Book>
<ID>1</ID>
<Name>Abhinav</Name>
<Author>Abhinav</Author>
</Book>

2)
{
   "ID" : 1,
   "NAME" : "Abhinaw"
   "Author": "Abhinaw"
}

In REST systems you can use either of the methods or both the methods depending on the requesting client to represent the data.

3) Messages: The client and server talk with each other via messages in which the client sends a message to server which is often called as request and the server sends a response.
 The actual data exchange between the client and server in the form of request and response body.there is some metadata exchange by the client and the server both in the form of request and response headers.

Sample Response:

{"result":{"alias":"bcpartner1_key.p12","creationDate":null, "dn":"cn=Trading Partner One,ou=BusinessConnect Server (only for TEST purposes),o=TIBCO Software Inc.,l=Palo Alto, st=California,c=US serial #7a3ed2ea20", "encryptionAlgorithm":0,"encryptionKeyFingerprint":"","encryptionKeyID":"","encryptionKeyLength":0, "expiryDate":{"date":31,"day":2,"hours":10,"minutes":52,"month":11,"seconds":13,"time":1735671133000, "timezoneOffset":480,"year":124}, "password":"IRbb9HE1NlLhs+HyIQ1jQ8Fg9FfC+hxnAgSCfUKB7xPe1xNUDKF/w==", "priCredContent":"MIIOQQIBAzCCDgcGCSqGSIb3DQEHAaCCDfgEgg30MIIN8DCCAukGCSqGSIb3DQEHAaCCAtoEggLWMIIC0jCCAs4GCyqGSIb3DQEM CgECoIICpjCCAqIwHAYKKoZIhvcNAQwBAzAOBAh/g3eJa5dMVQICB9AEggKAmwKc9/j/bZjAkGauBJo1yYeWOYsbB2iq6FDe0o+/HitTzIiWPJyLfOnO4G Y6me2qtcXF6d7Yx6qN3W3xkGbLiUeYQtnnxMFtnkD1+DRqWKIXmo1r8loTZntyKPdenVPkmFri06Nmdc7zDyRIkncz9nmZT/+iJHkGvQsdtbDT+hrLz1yD zeyqX7YUdCavkToQ5W9S57lVxn4ajKup8Xr+=", "pubCredContent":"","shadowExpiryDate":null,"shadowName":"","signingAlgorithm":0,"signingKeyFingerprint":"", "signingKeyID":"","signingKeyLength":0,"type":"KCRED","updatedFileName":"bcpartner1_key.p12","userID":""}}

4) Links Between Resources: A resource is an object with a type of associated data. and relationships to other resources alongside a set of methods that can be executed on it. The resources in REST API can contain link to other resources which should drive the process flow.

5)Caching: Caching is a technique that stores a copy of the given resource and serves it back when requested again. Saving extra DB calls and processing time. It can be done at different levels like client-server or middleware proxy server. Caching is important for API to increase its performance and scaling. Caching in REST APIs is controlled using HTTP headers. In REST specification when a safe method is used on a resource URL, usually the reverse proxy caches the results to use the cached data when the same resource is requested the next time.

6)Stateless: Each request from the client to the server must contain all of the information necessary to understand the request and can not take advantage of any stored context on the server.
Session state is therefore kept entirely on the client Statelessness here means that every HTTP responses is a complete entity in itself and enough to serve the purpose. The point of statelessness is to defeat the purpose of accord with the server allowing intended flexibility in the infrastructure. Statelessness is an essential part of being able to scale the infrastructure enabling us to deploy multiple servers to serve millions of concurrent users given there is no server session state dependency.






Conclusion 

Once you have Flask installed in your virtual environment you are ready to go the next step of the development phase. In the next part, I will discuss the Database because it is an essential part of the REST application.






No comments: