- 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:

推薦閱讀
- 程序員修煉之道:程序設(shè)計(jì)入門(mén)30講
- DBA攻堅(jiān)指南:左手Oracle,右手MySQL
- JavaScript從入門(mén)到精通(微視頻精編版)
- 深度學(xué)習(xí)經(jīng)典案例解析:基于MATLAB
- Leap Motion Development Essentials
- 基于免疫進(jìn)化的算法及應(yīng)用研究
- Linux環(huán)境編程:從應(yīng)用到內(nèi)核
- Quarkus實(shí)踐指南:構(gòu)建新一代的Kubernetes原生Java微服務(wù)
- Python編程實(shí)戰(zhàn)
- PHP+MySQL+Dreamweaver動(dòng)態(tài)網(wǎng)站開(kāi)發(fā)從入門(mén)到精通(第3版)
- HTML5+CSS3+jQuery Mobile APP與移動(dòng)網(wǎng)站設(shè)計(jì)從入門(mén)到精通
- Spring Boot從入門(mén)到實(shí)戰(zhàn)
- 虛擬現(xiàn)實(shí)建模與編程(SketchUp+OSG開(kāi)發(fā)技術(shù))
- Offer來(lái)了:Java面試核心知識(shí)點(diǎn)精講(框架篇)
- 從零開(kāi)始學(xué)Unity游戲開(kāi)發(fā):場(chǎng)景+角色+腳本+交互+體驗(yàn)+效果+發(fā)布