DEV Community

Cover image for Flask Rest API -Part:1- Using MongoDB with Flask

Flask Rest API -Part:1- Using MongoDB with Flask

Paurakh Sharma Humagain on December 13, 2019

Part 1: Using MongoDB with Flask Howdy! In the last Part of the series, we learned how to create a basic CRUD REST API functionality usi...
Collapse
 
ikhrome profile image
Ivan Khromov • Edited

Helpful note to everyone, who wants MongoEngine to serialize JSON like this:

{
    "id": "5f0b54728a42acf154e2082d",
    // the rest of document
}
Enter fullscreen mode Exit fullscreen mode

not this:

{
    "_id": {
        "$oid": "5f0b54728a42acf154e2082d"
    }
    // ... the rest of document
}
Enter fullscreen mode Exit fullscreen mode

Install MongoEngine GoodJSON library and extend Movie class like this:

from .db import db
import mongoengine_goodjson as gj

class Movie(gj.Document):
#the rest of code here ...
Enter fullscreen mode Exit fullscreen mode
Collapse
 
paurakhsharma profile image
Paurakh Sharma Humagain

Wow, that's cool. Thank you.
I was doing manual normalization, but this looks awesome.

Collapse
 
benayat profile image
benayat

thanks alot, I really like your style.
about the folder structure - in the begining, is says that the file models.py is inside the database folder, but than later - it says that "models" is the folder: dev.to/paurakhsharma/flask-rest-ap...
which is it?
plus, I'm working with vscode, and in the file "models.py", it doesn't recognize StringField at all. should it? or am I missing something?

Collapse
 
paurakhsharma profile image
Paurakh Sharma Humagain

Thank you so much, Sorry for the confusion.
models.py is a file. You can see the full code for this part here: github.com/paurakhsharma/flask-res...

Collapse
 
benayat profile image
benayat

I did, thanks. on one hand, it's the most comprehensive flask rest-api tutorial I found online, and that's a lot, really. I could learn in a few days everything I needed. but on the other hand, respectfully, it looks like you just quit after first draft...error handling not working, typos, and no edits regarding comments...
you'll probably spend more time on answering comments...it could be so much more

Thread Thread
 
paurakhsharma profile image
Paurakh Sharma Humagain

Yeah you are right, I should update the post for newer version of packages and fix some bugs, typos.
I got distracted with other things so couldn't give much attention to this tutorial. I will try to get some time soon to work on those. Really appreciate your criticism. Thanks! Have a great day.

Collapse
 
jestemkioskiem profile image
Jestemkioskiem • Edited

This is by far the best resource for learning how to do proper JWT Authorization and Authentication in Flask. I've spent hours looking at different tutorials with dubious solutions and not once did I hear about flask_jwt_extended. Thanks a lot!

One thing you might want to update, @jwt_required is now @jwt_required() in newer versions of flask_jwt_extended.

Collapse
 
engmsilva profile image
Marcelo Ribeiro da Silva

Great article,

I tried to make some changes to the parameters of the fields in the document, but it doesn't seem to have any effect

I removed the "required" parameter from the fields and there was no effect. How can changes be made to an existing document?

Collapse
 
paurakhsharma profile image
Paurakh Sharma Humagain

It's probably because when you give constrains to the field like required, mongodb creates an index for the field. So, to make the change take place you either have to delete the index or easier thing will be to delete the database (don't do that in production 😉)

Please let me know if deleting the index or the database solves your issue.

Collapse
 
engmsilva profile image
Marcelo Ribeiro da Silva

I had already tried to delete the bank and the index, but I was looking for an alternative to a document that cannot be deleted.

Collapse
 
therealibukun profile image
the-real-ibukun

Really helpful,
Some section of the code is omitted here, saved by the complete code on github though.
Thanks again.

Collapse
 
paurakhsharma profile image
Paurakh Sharma Humagain

Thank you so much ❤️
Can you point me what is missing so that I can add it here.

Collapse
 
therealibukun profile image
the-real-ibukun • Edited

Missing function definition add_movie()

@app.route('/movies', methods=['POST'])
body = request.get_json()
movie = Movie(**body).save()
id = movie.id
return {'id': str(id)}, 200

.movie not required

from database.models.movie import Movie

Apart from that it's ready to run 😃

Collapse
 
boredomdenied profile image
boredomdenied • Edited

I'm getting this error:

TypeError: TopLevelDocumentMetaclass object argument after ** must be a mapping, not NoneType

update

has been resolved by adding force=True

body = request.get_json(force=True)
Collapse
 
paurakhsharma profile image
Paurakh Sharma Humagain

Awesome 👍 Glad that you got it to work. I am not sure how you got this problem. Maybe something to do with your request body?

Collapse
 
rohansawant profile image
Rohan Sawant

Nice!

Embedding git diffs, into blog posts? Hmm, that's something I had never thought of before.

I am borrowing that some time!

🤗

Collapse
 
paurakhsharma profile image
Paurakh Sharma Humagain

Yeah, I thought it would make following the code changes easier 😃

Collapse
 
keshavadk profile image
keshavadk • Edited

Thank you for this clear explanation.

Can you make the "Flask REST API using Pymongo"?

Collapse
 
paurakhsharma profile image
Paurakh Sharma Humagain

Using pymongo is almost similar to Mongoengine, mongoengine only makes it easier to do stuffs....
I will try to make one article to show how to use Flask with Pymongo.

Collapse
 
keshavadk profile image
keshavadk • Edited

Ok. Thank you.

Collapse
 
mishra_amrish profile image
Amrish Mishra

I wish to have configuration structure using PyMongo

Collapse
 
thebadcoder profile image
TheBadCoder

Can you please explain-
initialize_db(app)

Collapse
 
paurakhsharma profile image
Paurakh Sharma Humagain • Edited

initialize_db() is a function that we created in movie-bag/database/db.py

Which starts the database connection :)