Search code examples
jsonflaskpostpostmanpymongo

POST request TypeError with PyMongo on Postman


Here's my code so far:

from flask import Flask, request, jsonify
from flask_pymongo import PyMongo, ObjectId
from flask_cors import CORS
import pymongo

app = Flask(__name__)
app.config["MONGO_URI"]="mongodb+srv://<USER>:<PASSWORD>...etc"
mongo = PyMongo(app)

CORS(app)

db = mongo.db.users

@app.route('/users', methods=['GET', 'POST'])
def createUser():
    if request.method == "GET":
            return jsonify({'msg': 'Successful GET response'})
    elif request.method == "POST":
        id = db.insert_one({
            'username': request.json['username'],
            'firstName': request.json['firstName'],
            'lastName': request.json['lastName'],
            'dob': request.json['dob']
        })
        return jsonify({'id': str(ObjectId(id)), 'msg': 'User Added Successfully!'})

#run app
if __name__ == "__main__":
    app.run(debug=True)

When I attempt a POST request on Postman at the url "/users" it gives me the following 500 Error response:

TypeError: id must be an instance of (bytes, str, ObjectId), not <class 'pymongo.results.InsertOneResult'>

I'm following a tutorial that uses .insert() instead of the newer .insert_one() or .insert_many(), I wonder if this has any relation to the issue.

Any help is appreciated!


Solution

  • I got it. All I had to do was switch

    return jsonify({'id': str(ObjectId(id)), 'msg': 'User Added Successfully!'})
    

    to

    return jsonify({'id': str(id.inserted_id), 'msg': 'User Added Successfully!'})
    

    Postman response:

    {
    "id": "6[...]b",
    "msg": "User Added Successfully!"
    }