📜 ⬆️ ⬇️

Creating a RESTful API in Google App Engine based on Flask


Gomez Julio Marillo de Servante is a well-known international drug lord who is concerned about the quality of the services provided by his organization. That's why he, Gomez, decided to develop a system of online orders for his partners.

Gomez's partners are located all over the world, they highly appreciate mobility (such is the specifics of business) and prefer to use mobile clients. Therefore, it was decided to develop a universal and simple API, to which each of the partners could access using any independently written solutions.

Requirements for the functionality of this API are absolutely insignificant. Just something to take orders. Therefore, it was decided to use the REST approach.
The http protocol, in addition to the well-known GET and POST methods, is able to use several other methods, such as PUT and DELETE.

When creating RESTful, we will adopt the following agreement regarding the methods:
POST - to create new entries.
GET - for recording information.
PUT - to make changes to the record.
DELETE - to delete records.
')
Gomez Julie Marillo is a very economical and technologically advanced person who knows the value of money, is not ready to pay for services more than it should be and is familiar with the concept of cloud technologies. On this choice immediately fell on Google App Engine .

But his subordinate developers (ie, we) are very lazy and do not want to do extra work. At the same time, they understand that there can be so much traffic, that using bulky solutions is simply not economical. They immediately adopted the Flask .
We were lucky, because Flask to work with WSGI uses Werkzeug , which is perfectly able to handle not only GET and POST, but also PUT and DELETE.

Your applaimer on the basis of the flask-skeleton for the app engine created your skeleton to create an API without blackjack and women .

Having made fork of the project we will start its modification.
First we need to develop an order model. Order is characterized by its unique number (it will be created by default), product name, weight and access key for modification . Open the application / models.py file and delete all its contents and write down:
from google.appengine.ext import db class Order(db.Model): title = db.StringProperty() weight = db.FloatProperty() token = db.StringProperty() 

Now let's work with urls.py. We need to add 3 handlers. For adding an order, obtaining information about the order and giving the order. Immediately after the line:
app.add_url_rule('/', view_func=views.home, methods=['GET',]) # Main page

Add the lines:
 app.add_url_rule('/drug/orders/', view_func=views.add_order, methods=['POST',]) app.add_url_rule('/drug/orders/', view_func=views.get_order, methods=['GET',]) app.add_url_rule('/drug/orders/', view_func=views.delete_order, methods=['DELETE',]) 


I will not give a description of the process of creating a form. It is quite travial.
It remains to create 3 corresponding functions in views.py. Let's start by adding an order:
 def add_order(): form = NewOrderForm() if form.title.data != "": drug_title = form.title.data else: return json_response({'error': 'Drug title is empty'}) if form.weight.data != "": drug_weight = form.weight.data else: return json_response({'error': 'Drug weight is empty'}) token = str(uuid.uuid4()) order = Order(title = drug_title, weight = float(drug_weight), token = token) order.put() return json_response({ 'id': int(order.key().id()), 'token': token, 'success': True }) 

Start the development server from the console (go to the project directory):
dev_appserver.py project_src/
Check the functionality of this function:
curl -d "title=drug1&weight=10" localhost:8080/drug/orders/
Result:
{"token": "2eac6ef6-198b-45a4-bab5-dd2c56d9fb0a", "id": 171, "success": true}
Wonderful. We proceed to the creation of a function that will provide us with order information:
 def get_order(): token = request.args.get('token') if token is None: return json_response({'error': 'Token is empty'}) order = Order.all().filter('token = ', token).fetch(1) if len(order) is 1: return json_response(order[0]._entity) else: return json_response({'error': 'Access denied'}) 

Checking:
curl -v -X GET localhost:8080/drug/orders/?token=2eac6ef6-198b-45a4-bab5-dd2c56d9fb0a
Result:
{"token": "2eac6ef6-198b-45a4-bab5-dd2c56d9fb0a", "weight": 10.0, "title": "value1"}
Finishing touch. Deleting an order:
 def delete_order(): token = request.args.get('token') if token is None: return json_response({'error': 'Token is empty'}) order = Order.all().filter('token = ', token).fetch(1) if len(order) is 1: order = order[0] order.delete() return json_response({'success': True}) else: return json_response({'error': 'Access denied'}) 

Checking:
curl -v -X DELETE localhost:8080/drug/orders/?token=2eac6ef6-198b-45a4-bab5-dd2c56d9fb0a
Result:
{"success": true}

Just in case, look at the database:


Once again the link to the source code of the project .

Comment.
Although this set of scripts is presented in a comic form, it can be expanded to almost any size of the API. I hope that I managed to write not a lot of letters, but at the same time giving you,% username%, an idea of ​​the process of creating a RESTful API in the cloud.

PS
To simplify the presentation and reduce the amount of code, we have slightly violated the REST principles. In particular, the “unambiguous identification of any resource”.

Source: https://habr.com/ru/post/141747/


All Articles