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

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:

主站蜘蛛池模板: 泰安市| 兴安县| 应城市| 翼城县| 徐汇区| 略阳县| 西林县| 封开县| 沁源县| 马龙县| 曲阜市| 清水河县| 商洛市| 盘锦市| 湛江市| 哈巴河县| 景德镇市| 辛集市| 丰都县| 苏州市| 遵义市| 新河县| 佛山市| 湖口县| 同心县| 新绛县| 勃利县| 五河县| 鄄城县| 万州区| 文山县| 台东县| 土默特左旗| 常德市| 鹤山市| 盱眙县| 大丰市| 沧源| 昭平县| 神农架林区| 石渠县|