0% found this document useful (0 votes)
7 views

5. REST - RESTful Web Services using Python

The document provides an overview of RESTful web services using Python, highlighting their purpose for machine-to-machine communication and the differences between web applications and web services. It details the characteristics of web services, types (SOAP and REST), and the methods for handling inputs and outputs in a Flask application. Additionally, it includes examples of RESTful web services with source code for both GET and POST requests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

5. REST - RESTful Web Services using Python

The document provides an overview of RESTful web services using Python, highlighting their purpose for machine-to-machine communication and the differences between web applications and web services. It details the characteristics of web services, types (SOAP and REST), and the methods for handling inputs and outputs in a Flask application. Additionally, it includes examples of RESTful web services with source code for both GET and POST requests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

| Rest Web Services using Python |

RESTFUL WEB SERVICES USING PYTHON

WEB SERVICE – MACHINE TO MACHINE COMMUNICATION


• It is a type of web application which is used to share the message
between client and server (Communication between two devices on a
network)
• Unlike web applications, the main benefit of web service supports the
code reusability. A single web service can be used by different kinds of
applications
• The main component of a web service is the data which is shared
between client and server
• It is a client server application for creating communication between two
devices over network for exchanging data.

• A web service is a software system designed to support interoperable


machine-to-machine interaction over a network.
• Generally, it is designed to be consumed by other applications or
services, often using XML (XML Web Service) or JSON (REST Web
Service) for data exchange.

1
| Rest Web Services using Python |

Characteristics
• No User Interface
▪ Web services do not have a GUI. They provide data and
functionality to other applications or services.
• Interoperability
▪ They are designed to be consumed by other applications,
regardless of the platform or language.
• Examples
▪ APIs for weather data, payment gateways, social media
integrations.
DIFFERENCE BETWEEN WEB APPLICATION AND WEB SERVICE
S.N Web Application Web Service
1. Purpose - Web applications are Purpose - Web services are
designed for human interaction. designed for machine-to-machine
It is a software application which communication over a network.
runs on a web server and is
accessed by a web browser
2. UI Interface – It has a user UI Interface – Usually it provides
interface (GUI) data and functionality without a
user interface
3. Usage - Web applications are Usage - Web services are
accessed via web browsers accessed via HTTP requests
(Ex. from other applications or
services)

• Both web applications and web services can be built using frameworks
like Flask in python, but they serve different purposes and are used in
different contexts.

2
| Rest Web Services using Python |

TYPES OF WEB SERVICES


• Web services come under two categories. They are
1. SOAP Based Services (XML Web Services)
2. REST Based Services
• Both services are two different ways to connect applications with server-
side data
1. SOAP Web Services (XML Web Services)
• SOAP stands for Simple Object Access Protocol
• This is XML based protocol for designing and developing web services.
• It is a platform and language independent as it is XML based
• It is an open standard protocol and provides data transport for web
services (Web services use SOAP protocol for sending the XML data
between applications)
2. REST Web Services (RESTful Web Services)
• REST stands for REpresentational State Transfer
• It is an architectural style for developing web services and popular web
services on current trends
• RESTful web services use HTTP requests to perform CRUD (Create,
Read, Update, Delete) operations.
• Web services that implement REST architecture are called as RESTful
web services
• These are generally designed to be consumed by other
applications or services, often using JSON for data exchange.
• They don't usually have a user interface (GUI).
Purpose
• REST web service is designed for machine-to-machine communication.
Data Format
• It typically uses JSON or XML for data exchange.

3
| Rest Web Services using Python |

Endpoints
• This provides CRUD operations (Create, Read, Update, Delete) via
HTTP methods (GET, POST, PUT, DELETE).
DIFFERENCES BETWEEN SOAP AND REST WEB SERVICES
S.N SOAP Services REST Services
1. SOAP stands for simple object REST stands for
access protocol (Structured representational state transfer.
protocol)
2. It is a protocol REST is an architectural style
3. It only supports XML format It supports various formats like
HTML, XML, JSON, Plain Text
etc,.
4. SOAP needs more bandwidth for its REST doesn’t need more
usage bandwidth
5. JAX-WS is the java API for SOAP JAX-RS is the java API for
web services REST
6. It is more secure than REST It is less secure than SOAP
7. Resources – XML & HTTP Resources – HTTP
8. It is used to transport data in XML Here it is used to transport
format data in JSON format which is
based on URI.
9. As it is XML based, it works with It works with HTTP GET,
WSDL (Web Service Description POST, PUT, DELETE methods
Language)
10. It can’t use REST because it is a REST can use SOAP web
protocol services and it can use any
protocols like HTTP, SOAP

4
| Rest Web Services using Python |

11. It uses service interfaces to expose It uses the URI (Uniform


the business logic Resource Identity) to expose
the business logic
12. It is less preferred than REST It is most preferred than SOAP.
It is most popular web services
on recent days

INPUTS IN RESTFUL WEB SERVICES


1. Inputs using Query Parameters (using GET Request)
• We can use query parameters to send input data to RESTful web service
in python. This involves using the GET method to send the form data
(user inputs).
2. Inputs using HTML Forms (using POST Request)
• We can use HTML forms to send data to RESTful web service in python.
This involves using the POST method to send the form data (user
inputs).

5
| Rest Web Services using Python |

I. EXAMPLE OF RESTFUL WEB SERVICES USING PYTHON FLASK


Tool / IDE used : VSC Editor
Application Type : Python Web Application
Web Framework : Flask
Type of Web Services : REST WEB SERVICES
Python Version : 3.11
Server Used : Built-in Flask Development
Server
Deployment Mode : Server Side Only
Tested OS : Windows 10
Type of Input Request : GET Request
Number of Routes : 3 (1 Home, 2 Contents)
PROJECT STRUCTURE

6
| Rest Web Services using Python |

2. SOURCE CODE
(home.html)
<html>
<center>
<body>
<h1 style="color: #bc0024;">Welcome to REST WEB SERVICES
using Python Flask</h1>
<h4><a href="add">Click to get Add Service</a></h4>
<h4><a href="mul">Click to get Mul Service</a></h4>
</body>
</center>
</html>
(hello.py)
# load necessary modules for python web framework for REST web service
from flask import Flask, request, render_template
# create an object for Flask Web
app = Flask(__name__)
# HOME PAGE
@app.route("/")
def home():
return render_template("home.html")
# CONTENT PAGE 1 (Route for addition)
@app.route('/add')  Create a route for the add() function
def add():
try:
# get two inputs from browser via Query String
a = int(request.args.get('a'))
b = int(request.args.get('b'))
result = a + b
7
| Rest Web Services using Python |

return "Sum: "+str(result)


except (TypeError, ValueError):
return "Input is not yet submitted."
# CONTENT PAGE 2 (Route for multiplication)
@app.route('/mul') # create another route for the mul() function
def mul():
try:
a = int(request.args.get('a')) # retrieve the value of “a” from the query
b = int(request.args.get('b')) # retrieve the value of “b” from the query
result = a * b
return "Mul: "+str(result)
except (TypeError, ValueError): Query parameters
return "Input is not yet submitted."

Alternatives Inputs
• Accessing request.args Directly - You can access the query
parameters directly from request.args which is a dictionary like object.

a=request.args[“a”]
b=request.args[“b”]

Where,
• a and b are user defined parameters.
• Using request.form – You can use request.form, if you are dealing
with form data (Ex. POST Request)

a=request.form.get(“a”)
b=request.form.get(“b”)

8
| Rest Web Services using Python |

• Using request.values – This is used to combine the input values from


request.args and request.form, allowing you to handle both query
parameters and form data.
• You can handle both types of input requests like GET, POST

a=request.values.get(“a”)
b=request.values.get(“b”)

Where,
• a and b are user defined parameters.
NOTE
• In flask web framework, a separate folder templates needs to created
manually in the current project directory to keep all design files like html
files, CSS files and many more.

9
| Rest Web Services using Python |

3. OUTPUT
3.1 HOME PAGE

10
| Rest Web Services using Python |

3.1 TESTING ADD SERVICE – AUTOMATIC CALLING FROM HOME


PAGE (WITHOUT INPUT SUBMISSION)

3.2 TESTING ADD SERVICE – INPUT SUBMISSION VIA QUERY STRING


MANUALLY (http://127.0.0.1:5000/add?a=25&b=25)

11
| Rest Web Services using Python |

3.3 TESTING MUL SERVICE – AUTOMATIC CALLING FROM HOME


PAGE (WITHOUT INPUT SUBMISSION)

3.4 TESTING ADD SERVICE – INPUT SUBMISSION VIA QUERY STRING


MANUALLY (http://127.0.0.1:5000/mul?a=25&b=25)

12
| Rest Web Services using Python |

Methods used in Flask Application


1. request.args.get()
• This is convenient way to handle query parameters
• This built-in method is used to retrieve a query parameters from the
URL in a flask application
• For example, in the URL http://127.0.0.1:5000/add?a=5&b=3, a and b
are query parameters.
NOTE
• You can test certain types of endpoints directly using a web browser, but
this is generally limited to GET requests.
• Postman or curl is recommended for testing more complex requests
especially for POST, PUT, and DELETE requests.
LIMITATIONS
POST, PUT, DELETE Requests:
• Browsers are not suitable for testing these types of requests directly.
• For these, you can use tools like Postman or curl, or you can create
simple HTML forms or JavaScript code to send these requests.

13
| Rest Web Services using Python |

II. EXAMPLE OF RESTFUL WEB SERVICES USING PYTHON FLASK


(HANDLING POST REQUEST USING HTML FORM)
Tool / IDE used : VSC Editor
Application Type : Python Web Application
Web Framework : Flask
Type of Web Services : REST WEB SERVICES
Python Version : 3.11
Server Used : Built-in Flask Development
Server
Deployment Mode : Server Side Only
Tested OS : Windows 10
Type of Input Request : POST Request
Number of Routes : 5 (1 Home, 4 Contents)

PROJECT STRUCTURE

14
| Rest Web Services using Python |

2. SOURCE CODE
(home.html)
<html>
<center>
<body>
<h1 style="color: #bc0024;">REST WEB SERVICES using Python
Flask (HTML FORM-POST)</h1>
<h4><a href="addUI">Click to get Add Service</a></h4>
<h4><a href="mulUI">Click to get Mul Service</a></h4>
</body>
</center>
</html>
(add.html)
<html>
<body>
<center>
<h1>Inputs Submission for Addition</h1>
<form action="addCode" method="post">
Number 1:<br>
<input type="text" size="35" name="n1"/><br>
Number 2:<br>
<input type="text" size="35" name="n2"/><br>
<input type="submit" value="Submit"/>
</form>
</center>
</body>
</html>

15
| Rest Web Services using Python |

(mul.html)
<html>
<body>
<center>
<h1>Inputs Submission for Multiplication</h1>
<form action="mulCode" method="post">
Number 1:<br>
<input type="text" size="35" name="n1"/><br>
Number 2:<br>
<input type="text" size="35" name="n2"/><br>
<input type="submit" value="Submit"/>
</form>
</center>
</body>
</html>
(calc.py)
from flask import *
# create an object for flask app
obj=Flask(__name__)
# create a home route
@obj.route("/")
def home():
# connect home page for list of operations
return render_template("home.html")
# content route 1 - define route for add UI
@obj.route("/addUI")
def addUI():
return render_template("add.html")

16
| Rest Web Services using Python |

# content route 2 - define route for add Logic


@obj.route("/addCode", methods=['GET','POST'])
def addLogic():
# get inputs from user via HTML UI
x=request.form["n1"]
x=int(x)
y=int(request.form["n2"])
c=x+y
return "<h1 style='color:violet'>Sum: "+str(c)+"</h1>"
# content route 1 - define route for add UI
@obj.route("/mulUI", methods=['GET','POST'])
def mulUI():
return render_template("mul.html")
# content route 2 - define route for add Logic
@obj.route("/mulCode", methods=['GET','POST'])
def mulLogic():
# get inputs from user via HTML UI
x=request.form["n1"]
x=int(x)
y=int(request.form["n2"])
c=x*y
return "<h1 style='color:red'>Product: "+str(c)+"</h1>"

17
| Rest Web Services using Python |

3. OUTPUT
3.1 HOME PAGE

3.2 INPUT SUBMISSION FOR SERVICE 1 – (UI Design)

18
| Rest Web Services using Python |

3.3 RESULT FOR ADD SERVICE

3.4 INPUT SUBMISSION FOR SERVICE 1 – (UI Design)

19
| Rest Web Services using Python |

3.5 RESULT FOR MULTIPLICATION SERVICE

20

You might also like