We can use the Flask library to create simple RESTful web services and web applications without having to install any complex web service engines or web application containers.
Listing 7.7 gives the code for a simple web service that gets a number as an input to the RESTful service, and outputs the Fibonacci number and Square of the number:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 7 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. from flask import Flask app = Flask(__name__) @app.route('/<int:num>') def index(num=1): return "Your Python Web Service <hr>Fibonacci("+ str(num) + "):
"+ str(fibonacci(num))+ "<hr>Square("+ str(num) + "):
"+ str(square(num)) def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) def square(n): print ("Calculating for the number %s" %n) return n*n
if __name__ == '__main__': app.run(debug=True)
If you run this recipe with a search tag and index, you can see some results similar to the following output:
$ python 17_7_create_restful_webservice.py * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 145-461-290 Calculating for the number 25 127.0.0.1 - - [15/Jun/2017 22:16:12] "GET /25 HTTP/1.1" 200 - 127.0.0.1 - - [15/Jun/2017 22:16:12] "GET /favicon.ico HTTP/1.1" 404 -
The output is shown in the following screenshot:
Instead of accessing the web service by the browser, you may also access it through curl.
Curl is very useful for testing RESTful web services. If it is not installed in your computer, you may install it using the following command:
$ sudo apt-get install curl
Once installed, you may access the RESTful interface of your application using curl:
$ curl -i http://127.0.0.1:5000/23 HTTP/1.0 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 67 Server: Werkzeug/0.12.2 Python/3.5.2 Date: Thu, 15 Jun 2017 21:16:07 GMT Your Python Web Service <hr>Fibonacci(23): 28657<hr>Square(23): 529
The output is displayed in the following screenshot: