I'm new to APIs and coding in general, so I'm really struggling with getting Flask and PyMongo to properly work together (since I don't know what I'm doing). I'm trying to just write a simple endpoint for a PATCH request. Code here:
@app.route('/update-instructor/<id>', methods=['PATCH'])
def update_one_instructor(id):
id = ObjectId(id)
id_call = {"_id" : id}
course = request.json.get("course")
email = request.json.get("email")
first = request.json.get("first")
last = request.json.get("last")
password = request.json.get("password")
role = request.json.get("role")
updateObject = {
"course": course,
"email": email,
"first": first,
"last": last,
"password": password,
"role": role
}
result = instructors.find_one_and_update(id_call, {"$set":updateObject}, return_document=ReturnDocument.AFTER)
return f'Instructor information updated {updateObject}'
However, when I pass this on to my database, it updates the fields I set, but sets everything else to 'null'. So if, in Postman, I submit:
{
"first" : "Jim"
}
It works, but every other field (that previously held values) become set to null. Obviously, I don't want to be setting every single key value pair in JSON when doing a PATCH request, right? What exactly is going on here?
My understanding of what I have written here is that it uses BSON to get the ObjectId and find the instructor, then each variable uses request.json to find what the current value is. Those are then passed into updateObject (which I would think defaults to the previously held values unless the body in Postman specifies otherwise...) and then passes that to the pymongo find_one_and_update method.
Please help out a newbie! Thanks!
CodePudding user response:
@app.route('/update-instructor/<id>', methods=['PATCH'])
def update_one_instructor(id):
request_params = request.get_json()
print(request_params)
# {'first': 'me', 'email': 'email'} only gives you the things from postman
updateObject = request_params
# updateObject = {
# "course": course,
# "email": email,
# "first": first,
# "last": last,
# "password": password,
# "role": role
# }
# Continue with your logic
return "Update Successful"
I put this in postman:
{
"first": "me",
"email": "email"
}