Web Services in Python

Umer Farooq
Feb 25, 2018 · 9 min read

Table of content

  • Web Service
  • REST and SOAP (Definition,Difference,usage)
  • Why we use Web service
  • GET and POST (Definition,Difference)
  • A sample Python Flask Application
  • What is Postman
  • JSON
  • XML
  • Image
  • Video Streaming

Web Services

In programming, generally refers to a web page, that can be called from an application (be it another web page, or desktop app), and the caller will pass in data to it, or receive data from it.It’s basically like a ‘method’ or ‘function’ in a normal programming language; except you’re calling it over the internet

Definations

A Web service is a software system designed to support interoperable machine-to-machine interaction over a network.

The term Web services describes a standardized way of integrating Web-based Application using the XML, SOAP, Wsdl and UDDIopen Standard over an Internet protocol Back.

What is REST

  • Everything in REST is considered as a resource.
  • Every resource is identified by a URI.
  • Uses uniform interfaces. Resources are handled using POST, GET, PUT, DELETE operations which are similar to Create, Read, Update and Delete (CRUD) operations.
  • Be stateless. Every request is an independent request. Each request from client to server must contain all the information necessary to understand the request.
  • Communications are done via representations.

What is SOAP

  • WSDL defines the contract between client and service and is static by its nature.
  • SOAP builds an XML based protocol on top of HTTP or sometimes TCP/IP.
  • SOAP describes functions and types of data.
  • SOAP is a successor of XML-RPC and is very similar, but describes a standard way to communicate.
  • Several programming languages have native support for SOAP, you typically feed it a web service URL, and you can call its web service functions without the need for specific code.
  • Binary data that is sent must be encoded first into a format such as base64 encoded.
  • Has several protocols and technologies relating to it: WSDL, XSD, SOAP, WS-Addressing.

SOAP vs REST?

One of the major benefits of SOAP is that you have a WSDL service description.

With RESTful services, message security is provided by the transport protocol (HTTPS) and is point-to-point only. It doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.

One of the major benefits of RESTful API is that it is flexible for data representation,

RESTful APIs are cleaner or easier to understand because they add an element of using standardized URIs and gives importance to HTTP verb used (i.e., GET, POST, PUT and DELETE).

RESTful services are also lightweight, that is they don’t have a lot of extra XML markup. To invoke RESTful API all you need is a browser or HTTP stack and pretty much every device or machine connected to a network has that.

Where to use REST

areas where REST works well for are:

  • Limited bandwidth and resources: remember the return structure is really in any format (developer defined). Plus, any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE verbs. Again, remember that REST can also use the XMLHttpRequest object that most modern browsers support today, which adds a bonus of AJAX.
  • stateless operations: if an operation needs to be continued, then REST is not the best approach and SOAP may fit it better. However, if you need stateless CRUD (Create, Read, Update, and Delete) operations, then REST is it.
  • Caching situations: if the information can be cached because of the stateless operation of the REST approach, this is perfect.

Where to use SOAP

areas where SOAP works as a great solution:

  • Asynchronous processing and invocation: if your application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Things like WSRM — WS-Reliable Messaging.
  • Formal contracts: if both sides (provider and consumer) have to agree on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
  • Stateful operations: if the application needs contextual information and conversational state management then SOAP 1.2 has the additional specification in the WS structure to support those things (Security, Transactions, Coordination, etc.). Comparatively, the REST approach would make the developers build this custom plumbing

why we use Web Service

Following are the three things why we use Web service:
1. Interoperability
2. Standardized Protocol
3. Low Cost of Communication

Interoperability
Web services allow various applications to talk to each other and share data and services among themselves. Other applications can also use the web services. For example, a VB or .NET application can talk to Java web services and vice versa. Web services are used to make the application platform and technology independent.
Standardized Protocol
Web services use standardized industry standard protocol for the communication. All the four layers (Service Transport, XML Messaging, Service Description, and Service Discovery layers) use well-defined protocols in the web services protocol stack. This standardization of protocol stack gives the business many advantages such as a wide range of choices, reduction in the cost due to competition, and increase in the quality.
Low Cost of Communication
Web services use SOAP over HTTP protocol, so you can use your existing low-cost internet for implementing web services. This solution is much less costly compared to proprietary solutions like EDI/B2B. Besides SOAP over HTTP, web services can also be implemented on other reliable transport mechanisms like FTP.

Two commonly used methods for a request-response between a client and server are: GET and POST.

  • GET — Requests data from a specified resource
  • POST — Submits data to be processed to a specified resource

Some features of GET requests are:

  • It remains in the browser history
  • It can be bookmarked
  • It can be cached
  • It have length restrictions
  • It should never be used when dealing with sensitive data
  • It should only be used for retrieving the data

Some features of POST requests are:

  • This requests cannot be bookmarked
  • This requests have no restrictions on length of data
  • This requests are never cached
  • This requests do not remains in the browser history

Python Flask

Flask is a simple, yet very powerful Python web framework.

Building web services with Flask is surprisingly simple, much simpler than building complete server side applications

for Installation use

First of all install :

pip install Flask

run a simple app (app.py)

#!flask/bin/python
from flask import Flask
app = Flask(__name__)@app.route('/')
def index():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)

When you execute app.py it will display following message

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) (copy paste the url in browser it will show Hello World)

What is Postman

Postman is a popular API client that makes it easy for developers to create, share, test and document APIs. This is done by allowing users to create and save simple and complex HTTP/s requests, as well as read their responses. The result — more efficient and less tedious work.

Postman is very convenient when it comes to executing APIs, since once you’ve entered and saved them you can simply use them over and over again, without having to remember the exact endpoint, headers, API key etc.

JSON

First of all, we need to import the Flask class from the flask module, so all the functionality we need becomes available. We will also import the request object from the flask module, which we will use later.

Then, we create an instance of the Flask class. In the constructor, we pass the name of the module of our application, using the __name__ global variable.

We will assume that the client will be posting JSON data, so we will specify a route that only answers to HTTP POST requests. Any GET request to the same URL will be ignored

First, to confirm if the content is of type JSON, we check the is_json attribute of the request object. This attribute indicates if this request is JSON or not.

To get the posted JSON data, we just need to call the get_json method on the request object, which parses the incoming JSON request data and returns it as a Python dictionary.

#!flask/bin/python
from flask import Flask
app = Flask(__name__)from flask import Flask
from flask import request
app = Flask(__name__)@app.route('/postjson', methods=['POST'])
def post():
print(request.is_json)
content = request.get_json()
#print(content)
print(content['id'])
print(content['name'])
return 'JSON posted'
app.run(host='0.0.0.0', port=5000)

When you execute app.py

We can test this code by using Postman, which allows us to do POST requests very easily. After installing this Chrome extension, open it

The “True” is the value of the is_json attribute, which indicates that the content was JSON.

XML

Flask-XML-RPC is an extension for Flask that makes it easy to create APIs based on the XML-RPC standard.

for Installation

$ pip install Flask-XML-RPC

A Simple Example

This is a REALLY simple example of how to create your own API using Flask-XML-RPC.

from flask import Flask
from flaskext.xmlrpc import XMLRPCHandler, Fault
app = Flask(__name__)handler = XMLRPCHandler('api')
handler.connect(app, '/api')
@handler.register
def hello(name="world"):
if not name:
raise Fault("unknown_recipient", "I need someone to greet!")
return "Hello, %s!" % name
app.run()

Images

First of all install :

pip install Flask-Uploads

Then in your main file ( app.py ) write code for upload image configurations :

from flask import Flask, render_template, request
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
app = Flask(__name__)photos = UploadSet('photos', IMAGES)app.config['UPLOADED_PHOTOS_DEST'] = 'static/img'
configure_uploads(app, photos)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
return filename
return render_template('upload.html')
if __name__ == '__main__':
app.run(debug=True)

then write html for image upload :

<html>
<head>
<title>Upload</title>
</head>
<body>
<form method=POST enctype=multipart/form-data action="{{ url_for('upload') }}">
<input type=file name=photo>
<input type="submit">
</form>
</body>
</html>

Run the server and upload the image. Upload images will save on static/img folder.

Video Streaming

Streaming is a technique in which the server provides the response to a request in chunks. I can think of a couple of reasons why this might be useful:

  • Very large responses. Having to assemble a response in memory only to return it to the client can be inefficient for very large responses. An alternative would be to write the response to disk and then return the file with flask.send_file(), but that adds I/O to the mix. Providing the response in small portions is a much better solution, assuming the data can be generated in chunks.
  • Real time data. For some applications a request may need to return data that comes from a real time source. A pretty good example of this is a real time video or audio feed. A lot of security cameras use this technique to stream video to web browsers.

Flask provides native support for streaming responses through the use of generator functions. A generator is a special function that can be interrupted and resumed. Consider the following function:

The example below shows how using streaming it is possible to generate a large data table, without having to assemble the entire table in memory:

from flask import Response, render_template
from app.models import Stock
def generate_stock_table():
yield render_template('stock_header.html')
for stock in Stock.query.all():
yield render_template('stock_row.html', stock=stock)
yield render_template('stock_footer.html')
@app.route('/stock-table')
def stock_table():
return Response(generate_stock_table())

In this example you can see how Flask works with generator functions. A route that returns a streamed response needs to return a Response object that is initialized with the generator function. Flask then takes care of invoking the generator and sending all the partial results as chunks to the client.

For this particular example if you assume Stock.query.all() returns the result of a database query as an iterable, then you can generate a potentially large table one row at a time, so regardless of the number of elements in the query the memory consumption in the Python process will not grow larger and larger due to having to assemble a large response string.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade