Creating a MongoDB-Backed RESTFul API With Python and Flask
<p>Im currently working on a MongoDB backed RESTFUL API with flask... However, Ive got a zone search query set up with find_one(), however as soon as I try making it a larger query with multiple results using find(), I get the following error on postman :</p>

<pre><code>UnboundLocalError: local variable 'output' referenced before assignment
</code></pre>

<p>this is the code that works, however it only returns one document from the query:</p>

<pre><code>@app.route('/active_jobs/&lt;zone&gt;', methods = ['GET'])
def get_one_zone(zone):

ajobs = mongo.db.ajobs

q = ajobs.find_One({'zone' : zone})

output = {}

output = ({
'zone': q['zone'], 'jobdate' : q['jobdate'],
'jobtime' : q['jobtime'],'client': q['client'],
})

return jsonify({output})
</code></pre>

<p>once I try to chage to get all results making it find() it doesnt work</p>

<pre><code>@app.route('/active_jobs/&lt;zone&gt;', methods = ['GET'])
def get_one_zone(zone):

ajobs = mongo.db.ajobs

q = ajobs.find({'zone' : zone})

output = {}

output = ({
'zone': q['zone'], 'jobdate' : q['jobdate'],
'jobtime' : q['jobtime'],'client': q['client'],
})

return jsonify({output})
</code></pre>

<p>Ps. Im a total newbie in the programming world so if you could use simple examples that would be much appreciated.</p>

<p>This is probably because 'find_One' in mongo will return only 1 document as a dictionary whereas find will return multiple documents as a list of dictionaries. jsonify does not work on a list as seen here: <a href="http://stackoverflow.com/questions/12435297/how-do-i-jsonify-a-list-in-flask">How do I `jsonify` a list in Flask?</a>.</p>

<p>You can use json.dumps instead as the answers there suggest.</p>

python mongodb rest api