REST API Stub with Flask

HTTP GET

By default Flask responds to GET.

Let us create the file server.py with the following code

from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello Flask!" if __name__ == "__main__": app.run()

If you see a manual without a method specified, keep in mind that it will either respond only to GET, or the author has changed the default settings.

You can run the server.py file with the command

python server.py

But traditionally flask run is used, which I describe in the article «The First Flask Project» .

If Flask is installed in your environment you will see

* Serving Flask app "server" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

You can open a browser and type http://127.0.0.1:5000/ into the address bar

The screen should show

Hello Flask!

And the console should show

127.0.0.1 - - [15/Jun/2020 16:19:06] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [15/Jun/2020 16:19:07] "GET /favicon.ico HTTP/1.1" 404 -

404 - because I did not add a favicon.ico file

A Simple Web Server in Flask

Creating such an elementary server that responds to requests is sometimes useful when you need to quickly test an application that, before sending some important information, requests the state of the server.

You can answer 200 and then listen to what the application sends.

from flask import request from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello world' @app.route('/bestws') def cakes(): return 'HeiHei.ru!' @app.route('/heiheiru/holidays', methods = ['GET']) def heiheiru_holidays(): timestamp = request.args.get('timestamp') print(f"Someone made a GET request to heihei.ru and passed the time {timestamp}") return '200' @app.route('/heiheiru/fests', methods = ['GET','PUT', 'POST']) def heiheiru_fests(): epc = request.args.get('epc') print(epc) antenna = request.args.get('antenna') print(antenna) timestamp = request.args.get('timestamp') print(timestamp) userMemory = request.args.get('userMemory') print(userMemory) return '200' if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')

Article author: Andrei Olegovich

Banner image