官术网_书友最值得收藏!

POST /api/v1/users

In this book, we go with the first approach to the POST method. So, let's define our route for the post method in app.py, and call the function to update the user record to the database file, as follows:

    @app.route('/api/v1/users', methods=['POST']) 
    def create_user(): 
      if not request.json or not 'username' in request.json or not
'email' in request.json or not 'password' in request.json: abort(400) user = { 'username': request.json['username'], 'email': request.json['email'], 'name': request.json.get('name',""), 'password': request.json['password'] } return jsonify({'status': add_user(user)}), 201

As you can see, in the preceding method, we called the exception with error code 400; let's write its handler now:

    @app.errorhandler(400) 
    def invalid_request(error): 
       return make_response(jsonify({'error': 'Bad Request'}), 400) 

We still need to define the add_user(user) function, which will update the new user record. Let's define it in app.py, as follows:

    def add_user(new_user): 
     conn = sqlite3.connect('mydb.db') 
     print ("Opened database successfully"); 
     api_list=[] 
     cursor=conn.cursor() 
     cursor.execute("SELECT * from users where username=? or
emailid=?",(new_user['username'],new_user['email'])) data = cursor.fetchall() if len(data) != 0: abort(409) else: cursor.execute("insert into users (username, emailid, password,
full_name) values(?,?,?,?)",(new_user['username'],new_user['email'],
new_user['password'], new_user['name'])) conn.commit() return "Success" conn.close() return jsonify(a_dict)

Now that we have added handler, as well as the route for the POST method of the user, let's test it by adding a new user using the following API call:

curl -i -H "Content-Type: application/json" -X POST -d '{
"username":"mahesh@rocks", "email": "mahesh99@gmail.com",
"password": "mahesh123", "name":"Mahesh" }'
http://localhost:5000/api/v1/users

Then, validate the user's list curl, http://localhost:5000/api/v1/users, as shown in the following screenshot:

主站蜘蛛池模板: 阿克苏市| 项城市| 城市| 蒙阴县| 年辖:市辖区| 广平县| 阜阳市| 阿鲁科尔沁旗| 东乡县| 苍山县| 吉水县| 武安市| 扶风县| 神农架林区| 隆子县| 桐柏县| 襄垣县| 同心县| 韶山市| 通化县| 佛坪县| 读书| 广昌县| 汶川县| 怀安县| 富阳市| 崇信县| 洪泽县| 神农架林区| 大关县| 塘沽区| 泗阳县| 玉山县| 内乡县| 宜城市| 定结县| 鸡西市| 祁东县| 平远县| 和平县| 平阴县|