1
RESTful web services
Dr. BRAHMI Zaki
zakibrahmi@gmail.com
Computer Science Departement,
College Of Science And arts at Al-Ola,
Taibah University
2
Goals
• Goals
– Understand the concepts and technology related to the web
service technology
– Master Restful service specification
– Develop and test Restful with Flask
3
Service
In the contexts of software architecture, service orientation and
service-oriented architecture:
• The term service refers to a set of software functionalities
(such as the retrieval of specified information or the execution of a set of
operations) with a goal that different clients can reuse for
different purposes.
• OASIS defines a service as "a mechanism to enable
access to one or more capabilities, where the access is
provided using a prescribed interface and is
exercised consistent with constraints and policies as
specified by the service description“ [source: OASIS
Reference Model for Service Oriented Architecture 1.0]
5
Service
a service is autonomous a service exposes a contract
General condition of sale,
Rules
Your right/Your duties
Borders between services Services communicate by
are explicit messages
Source A. Occello
6
Web Services
– A web service is a service provided by an independent separate
program that can be called by an application and can be run on
different machines
– Web Service is a technology:
• invoked service across the network
• Not based on content (web pages)
• Delivers structured data to an applications Web technologies to provide
functionality to another software application
– Définition [W3C]
• Is a software component identified by a URI,
• May be discovered by other software systems.
• May interact with other services in a manner imposed by their definitions,
using XML/JSON messages carried by Internet protocols.
Web Services
7
Web Service: Characteristics
• Reusable
• Machine-to-machine interactions
• Loose coupling:
– In software development, coupling typically refers to the degree to
which software components/modules depend upon each other. The degree
to which components are linked defines whether they operate in a tightly
coupled relationship or in a loosely coupled relationship.
– Loosely coupled components can operate independently from one another.
• Leveraging the architecture of the World Wide Web: http
• Interoperability: Interoperability is the ability of a system or a product to
work with other systems or products without special effort on the part of the
customer.
• Independently of The language, The platform (UNIX, Windows, ...), The
implementation (VB, C #, Java, ...), The underlying architecture (.NET, J2EE, ...)
RESTful web services
• Tow classes of web service: SOAP and RESTful
• REST- Representational State Transfer- is an
architectural style, not standard
• It was designed for distributed systems to address
architectural properties such as performance,
scalability, simplicity, modiability, visibility,
portability, and reliability
• System/API that conforms to the constraints of REST
can be called RESTful
RESTful web services
• REST is a web-based API format:
• Services provide resources (through URLs) designed to
be consumed by programs rather than by people
• REST vs Classical web
GET /index.html HTTP/1.1
Host: www.pitt.edu
Browser Web Server
HTTP/1.1 200 OK
Content-Type: text/html
Drawbacks:
<html> ….. </html>
• The client must understand both HTTP and HTML.
• The entire webpage is replaced with another one.
• Same data is usually sent in multiple responses.
• E.g. HTML code for the layout.
• What about Machine to Machine
RESTful web services
Main concepts
Resources
i.e., http://example.com/employees/12345
REST
Operations Representations
i.e., GET, POST i.e., XML, JSON
Ressource
• REST architecture treats every content as a resource.
• These resources can be Text Files, Html Pages, Images,
Videos , database object, etc.
• A ressource is identified by Uniform Resource
Identier (URI). Example:
• http://Taibah.edu.sa/students
• http:// Taibah.edu.sa /students /cs2650
As you traverse the path from more generic to more specific,
you are navigating the data
Ressource
Example of URI:
“books” is a collection of resources
“books/{id} is a singleton resource with id
Example google API: Driving directions
https://maps.googleapis.com/maps/api/directions/json?destination=ULA&origin=Tunisia
&key=YOUR_API_KEY
Ressource
Best Practices followed when designing a URI:
• Use nouns to represent resources rather than a verb
• Use consistent resource naming conventions to minimize
uncertainty and maximize readability and maintainability.
• /Users/admin/{user-id}/accounts
• /Users/admin/{user-id}/accounts/{account-id}
/Users/admin/u12345/accounts = > collection of accounts of the user u12345
• URI should follow a hierarchical structure (based on
structure-relationships of data)
Operations
• Operation are implementation of HTTP operations.
• Resource oriented, correspond to CRUD operations:
• GET
• POST
• DELTE
• PUT
Operations
Example: POST operation
States
Any invocation of the service return a code, which informs
clients of their request’s overarching result.
Example of codes:
2xx - success
200 OK - requests succeeded, usually contains data
201 Created - returns a Location header for new resource
202 Accepted - server received request and started processing
204 No Content - request succeeded, nothing to return
4xx - client error:
400 Bad Request { malformed syntax
401 Unauthorized { authentication required
403 Forbidden { server has understood, but refuses request
404 Not Found { resource not found
405 Method Not Allowed { specied method is not supported
Flask
Flask is a powerful and flexible micro web
framework for Python, ideal for both small and
large web projects.
https://flask.palletsprojects.com/en/3.0.x/
To install Flask in our virtual environment:
pip install flask
To create virtaul environement :
python -m venv myenv
More information: https://medium.com/@dipan.saha/managing-git-repositories-with-
vscode-setting-up-a-virtual-environment-62980b9e8106
Virtual environment
A virtual environment is a self-contained Python environment that allows you to
install and use different versions of Python and its libraries without affecting your
system Python installation.
To create a virtual environment on VSCode
1. Create a folder at any directory, example LoveFlask
2. Open LoveFlask by VSCode
3. Open powershell terminal within VSCode and create a virtual environment called,
for example myenv, using the commande: python -m venv myenv
4. Select the Python Interpreter:
view - Command Palette - Python: select interpreter –
5. Activate the virtual environment using the command: myenv\Scripts\activate.ps1
.
Example
# Importing flask module in the project is mandatory
from flask import Flask
# Flask constructor takes the name of
# current module (__name__) as argument.
app = Flask(__name__)
# The route() function of the Flask class is a decorator,
# which tells the application which URL should call the associated function.
@app.route('/')
# ‘/’ URL is bound with hello_world() function.
def hello_world():
return 'Hello Flask API’
# main driver function
if __name__ == '__main__’:
# run() runs the application on the local development server.
app.run()
Flask
To run the service: python nomfile.py
To call the service: http://localhost:5000/
Flask path parameters
• To pass parameters to your Rest API, you can use the route/path.
• A parameter can be a string (text) like this: /product/laptop
• Example:
@app.route('/product/<name>’, methods=['GET'])
def get_product(name):
return "The product is " + str(name)
Flask path parameters
Post method and data sent as JSON document
from flask import request, make_response, abort, Flask
app = Flask(__name__)
@app.route('/product/add', methods=['POST'])
def getProduct():
# get data sent as JSON data
data = request.get_json()
return data['name'] Path Method
if __name__ == '__main__':
app.run()
Flask path parameters
Call the API using Postman tool
Flask query parameters
Parameters can be sent using query parameters.
Parameters Values
Example:
http://localhost:5000/product/add?language=python&framework=flask
app = Flask(__name__)
@app.route('/product/add', methods=['GET'])
def getProduct():
# Retrieve parameters
arg1 = request.args.get('language')
arg1 = request.args.get('framework')
return arg1
30
End