- Cloud Native Python
- Manish Sethi
- 236字
- 2021-07-02 19:11:58
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:

推薦閱讀
- C語(yǔ)言程序設(shè)計(jì)案例教程
- 玩轉(zhuǎn)Scratch少兒趣味編程
- Java多線程編程實(shí)戰(zhàn)指南:設(shè)計(jì)模式篇(第2版)
- .NET之美:.NET關(guān)鍵技術(shù)深入解析
- Spring Cloud Alibaba核心技術(shù)與實(shí)戰(zhàn)案例
- Designing Machine Learning Systems with Python
- Android開(kāi)發(fā)精要
- WebAssembly實(shí)戰(zhàn)
- Twilio Best Practices
- Mastering Articulate Storyline
- 深入理解Java7:核心技術(shù)與最佳實(shí)踐
- AutoCAD VBA參數(shù)化繪圖程序開(kāi)發(fā)與實(shí)戰(zhàn)編碼
- Learning Apache Mahout Classification
- 學(xué)Python也可以這么有趣
- Yocto for Raspberry Pi