Python uses Flask to implement the RESTful API, Postman tools, requests library to test interfaces

RESTful is an API design specification.
In the RESTful architecture, four HTTP request modes, POST, DELETE, PUT and GET, are used to add, delete, and check the specified URL resources.

Prior to RESTful:

/users/query/1 GET Query user data based on user id
/users/save POST New Users
/users/update POST Modify user information
/users/delete GET/POST Delete user information

RESTful practices:

/users/1 GET Query user data based on user id
/users POST New Users
/users PUT Modify user information
/users DELETE Delete user information

For each request from the client, the server responds with an HTTP status code and data.
Partial status code:
GET: 200 OK
POST: 201 Created
PUT: 200 OK
DELETE: 204 No Content

 

An example of implementing a RESTful API service using Flask

from flask import Flask,jsonify,abort,make_response,request
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__)
auth = HTTPBasicAuth()

users = [
    {
        'id': 1,
        'username': 'Xiao Ming',
        'sex': 1
    },
    {
        'id': 2,
        'username': 'Little Red',
        'sex': 0
    }
]

#User name and password are required before accessing
@auth.get_password
def get_password(username):
    if username == 'admin':
        return '123456'
    return None

#Friendly error tip: No permissions
@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized'}), 403)

#Friendly error tip: No resource page found
@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Resource not found'}), 404)

#Return records for all users
@app.route('/api/v1.0/users', methods=['GET'])
@auth.login_required #Require authentication
def get_users():
    return jsonify({'users': users})

#Returns a user's record
@app.route('/api/v1.0/users/<int:user_id>', methods=['GET'])
@auth.login_required
def get_user(user_id):
    user = list(u for u in users if u['id'] == user_id)
    if len(user) == 0:
        abort(404)
    return jsonify({'user': user[0]})

#Insert a user record
@app.route('/api/v1.0/users', methods=['POST'])
@auth.login_required
def create_user():
    if not request.json or not 'username' in request.json or not 'sex' in request.json:
        abort(400)
    user = {
        'id': users[-1]['id'] + 1,
        'username': request.json['username'],
        'sex': request.json['sex']
    }
    users.append(user)
    return jsonify({'user': user}), 201

#Update a user's record
@app.route('/api/v1.0/users/<int:user_id>', methods=['PUT'])
@auth.login_required
def update_user(user_id):
    user = list(u for u in users if u['id'] == user_id)
    if len(user) == 0:
        abort(404)
    if not request.json:
        abort(400)   
    user[0]['username'] = request.json.get('username', user[0]['username'])
    user[0]['sex'] = request.json.get('sex', user[0]['sex'])
    return jsonify({'user': user[0]})

#Delete a user's record
@app.route('/api/v1.0/users/<int:user_id>', methods=['DELETE'])
@auth.login_required
def delete_user(user_id):
    user = list(u for u in users if u['id'] == user_id)
    if len(user) == 0:
        abort(404)
    users.remove(user[0])
    return jsonify({'result': True}),204


if __name__ == '__main__':
    app.run(debug=True)

 

Using Postman test interface

Create a new Request, Request name and Create Collection are freely entered such as RESTfulAPI, and after saving, automatically open a label page named RESTfulAPI.

(1) Test/api/v1.0/users GET requests

The RESTfulAPI tab defaults to GET, input: localhost:5000/api/v1.0/users, click Send button directly here, Postman return code: Status:403 FORBIDDEN, return content

{
"error": "Unauthorized"
}

In the Authorization Tag, TYPE selects Basic Auth, and on the right, Username and Password enter admin and 123 456, respectively.

 

Click Send button, Postman return code: Status:201 CREATED, return content:

{
  "users": [
    {
      "id": 1,
      "sex": 1,
      "username": "Xiao Ming"
    },
    {
      "id": 2,
      "sex": 0,
      "username": "Little Red"
    }
  ]
}

(2) GET requests tested/api/v1.0/users/<int:user_id>

Modify Postman's request method and address to GET localhost:5000/api/v1.0/users/2

(3) Testing/api/v1.0/users POST requests

Modify Postman's request method and address to POST localhost:5000/api/v1.0/users
Select raw in the Body tag, modify the last default Text to JSON(application/json), and fill in the following input boxes:

{
	"id": 3,
	"sex": 1,
	"username": "Cockroach"
}

Click Send button, Postman return code: Status:201 CREATED
Changing the POST method directly to the GET method returns three records.

(4) Test/api/v1.0/users/<int:user_id>PUT requests

Modify Postman's request method and address to PUT localhost:5000/api/v1.0/users/3
Select raw in the Body tag, modify the last default Text to JSON(application/json), and fill in the following input boxes:

{
	"id": 3,
	"sex": 1,
	"username": "Xiao Gang"
}

Click Send button, Postman return code: Status:200 OK

(5) DELETE request for test/api/v1.0/users/<int:user_id>

Modify Postman's request method and address to DELETE localhost:5000/api/v1.0/users/3
Click Send button, Postman return code: Status:204 NOT CONTENT

 

Testing interfaces using Python's third-party library requests

import requests,json

url = 'http://localhost:5000/api/v1.0'
auth = ('admin','123456')

#query
r=requests.get(url + '/users', auth=auth)
print(r.status_code, r.text)
#Chinese will be used when console output unicode Display, Chinese can be displayed in the following ways
#print(json.dumps(json.loads(r.text),ensure_ascii=False))

r=requests.get(url + '/users/1', auth=auth)
print(r.status_code, r.text)

#To update
data = {
    "id": 3,
    "sex": 1,
    "username": "Cockroach"
}
r=requests.post(url + '/users', auth=auth, json=data)
print(r.status_code, r.text)

#modify
data = {
    "id": 3,
    "sex": 1,
    "username": "Xiao Gang"
}
r=requests.put(url + '/users/3', auth=auth, json=data)
print(r.status_code, r.text)

#delete
r=requests.delete(url + '/users/3', auth=auth)
print(r.status_code, r.text)

Keywords: Python JSON

Added by sniped22 on Sun, 08 Sep 2019 08:42:33 +0300