REST API services let y'all interact with the database past simply doing HTTP requests. In this article you lot learn how to write a Residuum server using the Flask.

This is often how the backend of web apps is created. Returning data is in JSON format and requests we are using are PUT, DELETE, Postal service, and Get

If yous want to put your API online, apply: PythonAnywhere.

Related course: Python Flask: Create Web Apps with Flask

Flask API example

Introduction

To make our first program, recall that we enter the URL in the browser

                    one                    
                    localhost:5000                                        

At the time, a cord "Hello Globe!" was returned, so we thought, can we supervene upon this cord with a json sequence? Isn't that the aforementioned as a REST query API?

So, we might have the starting time impulse to do this:

                    1                    
2
three
four
5
6
7
viii
nine
10
                                        

import json
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index ():
return json.dumps({'proper name': 'alice',
'email': '[email protected]'})
app.run()

Actually, nosotros just modified the returned string, modified information technology to a string of JSON, and then we opened it on the browser

                    1                    
                    localhost:5000                                        

flask json

Wow! It seems to have achieved the function nosotros wanted, returned a JSON cord.

Just we opened the debug tool for Chrome (which I use as a tool like to Chrome, Safari, Firefox) (nether Windows: Ctrl + Alt + I, Mac under: Cmd + Shift + I), we tin can see that this returned information type really is of type html:

dev tools content type html

You may wonder what bear on this might have, the impact should exist small-scale in most cases, but for some mobile-side libraries, the data may be candy according to the response (incorrectly!).

If you lot desire to put your API online, use: PythonAnywhere.

Return json

To deal with this situation, we can't just prepare this response head into json format.
A better solution is to utilize the jsonify function of the Flask, where I use this part to modify the code:

                    one                    
2
three
4
v
half dozen
7
8
ix
10
11
                                        

import json
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def index ():
return jsonify({'proper name': 'alice',
'email': '[email protected]'})

app.run()

The changes are:

                    1                    
2
3
4
                                          from                      flask                      import                      ...., jsonify                    
... ...
return jsonify({'name': 'alice',
'e-mail': '[email protected]'})

flask json response

Look at Google Dev Tools, you'll run into the content-type modify to JSON.

google developer tools json response

Asking method

We know that there are 6 commonly used HTTP request methods, which are

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH
  • HEAD

The code that we just had had to deal with GET by default (the browser defaults to using Become), so how do you program the other requests?

Like this:

                    1                    
2
3
                                          @app.route('/', methods=['POST'])                                        
@app.road('/', methods=['DELETE'])
@app.route('/', methods=['PUT'])

The programme below demonstrates this:

                    1                    
2
three
4
five
six
7
8
9
x
11
12
thirteen
14
fifteen
16
17
18
nineteen
20
21
22
23
24
25
26
27
28
29
xxx
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fifty
51
52
53
54
55
56
57
58
59
60
61
62
63
64
                                        

import json
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.road('/', methods=['GET'])
def query_records ():
proper name = asking.args.get('proper noun')
print name
with open('/tmp/data.txt', 'r') as f:
information = f.read()
records = json.loads(data)
for record in records:
if tape['name'] == name:
render jsonify(tape)
return jsonify({'error': 'data not found'})

@app.route('/', methods=['PUT'])
def create_record ():
record = json.loads(request.data)
with open('/tmp/data.txt', 'r') as f:
information = f.read()
if not data:
records = [record]
else:
records = json.loads(data)
records.suspend(record)
with open('/tmp/data.txt', 'w') as f:
f.write(json.dumps(records, indent=2))
return jsonify(record)

@app.route('/', methods=['Mail'])
def update_record ():
record = json.loads(request.data)
new_records = []
with open up('/tmp/data.txt', 'r') as f:
information = f.read()
records = json.loads(information)
for r in records:
if r['proper noun'] == record['proper noun']:
r['e-mail'] = record['email']
new_records.suspend(r)
with open('/tmp/data.txt', 'w') as f:
f.write(json.dumps(new_records, indent=two))
render jsonify(record)

@app.route('/', methods=['DELETE'])
def delte_record ():
record = json.loads(request.information)
new_records = []
with open up('/tmp/information.txt', 'r') as f:
information = f.read()
records = json.loads(information)
for r in records:
if r['proper name'] == record['name']:
continue
new_records.append(r)
with open up('/tmp/data.txt', 'w') as f:
f.write(json.dumps(new_records, indent=two))
render jsonify(record)

app.run(debug=True)

The code is long, merely the lawmaking is easier to empathize, and it is a relatively unproblematic file operation.

The code that we need to focus on is the post-obit:

  • How to ready request methods
                    1                    
two
3
4
                                          @app.road('/', methods=['GET'])                                        
@app.route('/', methods=['PUT'])
@app.route('/', methods=['POST'])
@app.route('/', methods=['DELETE'])
  • How to get data

If you want to put your API online, use: PythonAnywhere.