REST API With Flask & SQL Alchemy

Sdílet
Vložit
  • čas přidán 29. 07. 2024
  • In this project we will use Python Flask along with SQL Alchemy and Marshmallow to create a RESTful API for products.
    Sponsor: Freelancer Bundle (Use "brad25" for 25% off)
    studywebdevelopment.com/freel...
    Code:
    github.com/bradtraversy/flask...
    Flask From Scratch Series:
    • Python Flask From Scra...
    💖 Become a Patron: Show support & get perks!
    / traversymedia
    Website & Udemy Courses
    www.traversymedia.com
    Follow Traversy Media:
    / traversymedia
    / traversymedia
    / traversymedia
  • Věda a technologie

Komentáře • 374

  • @1cannon3
    @1cannon3 Před 5 lety +184

    0:27 - Intro to tutorial
    1:00 - Intro to the other packages used in this tutorial (SQLAlchemy, Marshmallow, PostMan)
    2:01 - Creating virtual environment (Pipenv)
    3:09 - Installing dependencies
    4:10 - Create main file (app.py)
    5:43 - Initialize flask and run server
    7:02 - Creating a basic route
    7:58 - Making POST request in Postman
    8:18 - Setting up database URI
    9:04 - Setting up database
    10:46 - Initialize database
    11:00 - Initialize Marshmallow
    11:23 - Creating a class for your resource(s)
    16:13 - Creating a product schema (This is where we use Marshmallow)
    17:13 - Initialize schema
    17:56 - Another schema initialization
    18:50 - Creating the database
    20:04 - Creating our routes
    20:15 - "Create a product" route ('/product')
    23:30 - Making a POST request in Postman
    24:50 - Creating "fetch all products" route
    25:40 - SQLAlchemy .all() method
    26:46 - Testing get all products in Postman
    27:28 - Creating "get single product" route
    29:29 - Creating "update a product" route
    31:35 - Making a PUT request to product in Postman
    32:21 - Create a delete route
    33:49 - Making a DELETE request in Postman

    • @default_youtube_profile
      @default_youtube_profile Před 4 lety +1

      Everything is easy if you put them in a single module, you should organise your app in a proper structure and then explain what you are doing.

  • @MoltiSanti
    @MoltiSanti Před rokem +20

    If when running "db.create_all()" from the Python interpreter you experience "RuntimeError: Working outside of application context.", instead run the following three lines:
    >>> from app import app, db
    >>> app.app_context().push()
    >>> db.create_all()

  • @SimonMarkHolland
    @SimonMarkHolland Před rokem +10

    Another great video thank you.
    If anyone gets the error "AttributeError: 'list' object has no attribute 'data'", it's because since Marshmallow v3 you don't need the .data attribute as dump returns the data directly ...
    def get_products():
    all_products = Product.query.all()
    result = products_schema.dump(all_products)
    return jsonify(result)

  • @ruudhermans4243
    @ruudhermans4243 Před 3 lety +7

    For people coming across this video in June 2021. I had a few issues using the latest versions of everything.
    1. At 18 minutes the schema no longer requires strict = True.
    2. At 16.30, result.data should be result.

  • @nickapeed
    @nickapeed Před 2 lety +11

    For anyone using this now, and update to Marshmallow (from documentation):
    Setting the strict option on class Meta has no effect on Schema behavior. Passing strict=True or strict=False to the Schema constructor will raise a TypeError.

  • @MaxProgramming
    @MaxProgramming Před 2 lety +8

    Just for someone who gets stuck when they get all products, the "result" variable will be default be an array/list so you don't need the `data` you can just jsonify(result)

  • @Ambrozekwerondaa
    @Ambrozekwerondaa Před 5 lety +4

    Hi Traversy, Thanks so much for this video. I had been reading a lot and trying to get the concept of such an API but it was confusing to me mostly because many tutorials start off by putting different things in different files and then they import different modules into each other-it's just too confusing for a beginner. So thanks to God you put everything in a single file and gave us an overview. You have no idea how that is important to me.

  • @bureaucafeatelier5603
    @bureaucafeatelier5603 Před 3 lety +9

    Quite old, some methods are not the same right now. But it's definitely a good tutorial.
    The strict param is not accepted right now for marshmallow (product(s)_schema)
    For the get_all the following lines are the new ones:
    all_products = Product.query.all()
    return products_schema.jsonify(all_products)

  • @johncrunk8038
    @johncrunk8038 Před 3 lety +7

    Thank you for presenting an example by using my favorite two tools - pipenv and vscode. They save so much time and effort. I also ALWAYS create a git repository for projects, even if they are the throwaway kind. As of this date, marshmallow is version 3.0 and the "strict" key is no longer needed or allowed.

  • @imbayi
    @imbayi Před 5 lety +93

    This channel is the gift that keeps giving.

    • @yomajo
      @yomajo Před 4 lety

      Make sure you give back ;)

  • @IGEDEWICAKSANA
    @IGEDEWICAKSANA Před 5 lety +3

    Thank you Brad, i learn anything from node js, react js, and today currently learn python(flask) from you. I prefer with how you teach some thing

  • @zb2747
    @zb2747 Před 2 lety +1

    Thank you! I’m coming from node web backends and just tryna switch it up and start using python instead. Most tutorials were just brushing over the basics without explaining and getting straight to the point. Thank you brad, you’re THE best!

  • @ua83
    @ua83 Před 4 lety +94

    Thanks for the video Brad. kudos.
    I was getting this error when sending a GET to return all the Products,
    To fix it I returned jsonify(result) instead of jsonify(result.data)
    I hope it will save someone else time
    =)

    • @johnnysim1985
      @johnnysim1985 Před 4 lety +5

      Came here to find this exact problem

    • @fun2badult
      @fun2badult Před 4 lety +2

      this solved my issue too of not finding 'data'

    • @woltron4o
      @woltron4o Před 4 lety +1

      This was my last issue with the code. Thanks.

    • @parsonsmarcus
      @parsonsmarcus Před 4 lety +2

      I was just about to comment this myself. Cheers!

    • @malamhari_
      @malamhari_ Před 4 lety +2

      You save my time, thanks

  • @MegaCookiecook
    @MegaCookiecook Před 2 lety +1

    Still useful in 2022. Thanks so much for this tutorial. I can't believe how easy this was to implement.

  • @askmehow25
    @askmehow25 Před 4 lety

    Thank you so much for this.
    As a part of an interview assignment, I was given a task to create a CRUD system and expose APIs for a table.
    Starting from absolutely 0 knowledge about Flask, I was able to fully develop it thanks to you.
    Thank you so much!
    Do let me know if there is some way I can buy you a couple of beers (your Paypal?)

  • @enosaeon118
    @enosaeon118 Před 5 lety +1

    I am currently studying this same topic, great having Brad’s take on it.

  • @chadelofson1637
    @chadelofson1637 Před 5 lety +1

    Thanks for a quick introduction to Flask REST API. I am working on a React/Flask application for IT Inventory system. I was looking for something quick on Flask REST API development.

  • @chinmoyjyotikathar8793
    @chinmoyjyotikathar8793 Před 3 lety +5

    For anyone confused about how the table name is generated, I just realized that on executing the db.create_all() command, a table with same name as the lower cased Class name gets created in SQLite database, so in this case a table named 'product' is created with the defined schema. Also, if Class name has a name like MyProduct then table would be named as my_product.

  • @Lerklinten
    @Lerklinten Před 3 lety +2

    Once again a simple and perfect demonstration, love your work! Keep it up

  • @jonealbrown1481
    @jonealbrown1481 Před 5 lety +3

    My lunch break well spent watching another Brad tutorial!

  • @frikishaan
    @frikishaan Před 5 lety

    This year is going to be awesome for your students first React and now this. Thanks Sir!

  • @senned27
    @senned27 Před 5 lety +6

    I would really appreciate a tutorial on how this could work with NoSQL! Great work, Brad.

  • @kaiman6539
    @kaiman6539 Před 5 lety

    I m currently working on a project with the exact same tools and man I needed a video like this on

  • @mahmoudtokura
    @mahmoudtokura Před 5 lety +4

    Awesome tutorial, it clearly shows why Flask is the best framework for python API development.
    You can also use Flask-Restful to define your endpoints.
    It give you all the HTTP verbs ready, your endpoints will be called resources rather than routes.
    Thanks Brad for your hard work and dedication.

    • @12PnT12
      @12PnT12 Před rokem

      I was introduced to FastAPI and never want to look back! It feels like a sucessor to flask: inspired by it, but adding a lot of structure and validation with parameters and type hints.

  • @mahmudulhassan9043
    @mahmudulhassan9043 Před 5 lety +2

    Ohhhh Thankssss Brad .You are the best .I am just Searching for this tutorial ......Love you man...

  • @k.santiagodiaz3744
    @k.santiagodiaz3744 Před 4 lety

    Flask is ridiculously simple to work with Rest APIs. So grateful with this tutorial

  • @shashikanth8605
    @shashikanth8605 Před 4 lety +1

    It's showing an error like "Instance of 'SQLAlchemy' has no 'Column' member" what should i do ?

  • @idembele
    @idembele Před 5 lety

    Thank you Brad.
    what if i had to connect to a remote MySQL server. SQL ALCHEMY can still connect to a distant host?

  • @Vt12365
    @Vt12365 Před 2 lety +5

    18:00 - When initialising the schema object, the strict argument is no longer valid, for the newer versions of SQLAlchemy.

    • @mpilodlamini8407
      @mpilodlamini8407 Před 2 lety +1

      Thank you very much for that. I removed strict=True for now

  • @TheCodebookInc
    @TheCodebookInc Před 5 lety +9

    I really love Flask coz it's is similar to express when it comes to build apis but I would love to watch a video with authentication added to this via Rest. Anyways your contents are making our lives in this competitive world easier. Thanks teacher

  • @adsbix5337
    @adsbix5337 Před 5 lety

    thank you so much sir , It's easy to use, and feels modern and natural.

  • @hakusho04
    @hakusho04 Před 3 lety +2

    For anyone following this tutorial in 2021 The strict parameter was removed. Schemas are always strict.
    So
    product_schema = ProductSchema()
    products_schema = ProductSchema(many=True)

  • @sheetaljade1440
    @sheetaljade1440 Před 3 lety

    Thanks for very nice explanation. It is explained in such a way that beginner gets confidence to go ahead without any frustration.

  • @geeksy2278
    @geeksy2278 Před 5 lety +1

    Pipenv is my fav package at the moment! So awesome!

  • @himanshukarki
    @himanshukarki Před 5 lety

    Great Video man... keep the good work. It was a really really good learning. Many thanks for putting this effort and spreading useful knowledge.

  • @krisdtrades
    @krisdtrades Před 3 lety

    Watched this late, but the information is still relevant! A life save! Thanks Brad!

  • @christopherbell2176
    @christopherbell2176 Před 4 lety

    This is a great tutorial. Thanks for putting this up. Definitely saving this video.

  • @tylorg7971
    @tylorg7971 Před 5 lety

    I was watching your other flask tutorial just the other day, so this video came at the perfect time. Thanks, Brad! I've even been telling my girlfriend about you.

  • @TommyReady
    @TommyReady Před 3 lety

    Great video. This looks so simple I wish I could find a gig doing Python and Flask everyday :)

  • @leootp22
    @leootp22 Před 5 lety +1

    Thanks for the awesome vid, really easy to follow and learned so much

  • @nassav3
    @nassav3 Před 5 lety

    Awesome video! I have been wondering how to make a API. Thank you !

  • @JohnLednicky
    @JohnLednicky Před 2 lety +2

    Breaking Marshmallow changes since the version used to record this tutorial.
    3.0.0b7 (2018-02-03)
    Features:
    Backwards-incompatible: Schemas are always strict (#377). The strict parameter is removed.
    Backwards-incompatible: Schema().load and Schema().dump return data instead of a (data, errors) tuple (#598).

  • @Galahadoc
    @Galahadoc Před 4 lety

    This was a great video that explained some elements that I hadn't quite grasped within my existing API. Covered all CRUD scenarios however I feel "Add Multiple Products" would have just finished those scenarios off.

  • @daniestrijdom8248
    @daniestrijdom8248 Před 4 lety

    how would you add a script that would create the db if it doesn't exist and you are in debug more?for instance if you dockerize this and want to just run the container and have it do the things straight away. I suppose another python file in your dockerfile?

  • @penmaipottru9590
    @penmaipottru9590 Před 4 lety

    Great Tutorial for the Flask beginners! Thanks a lot.

  • @adriansun2999
    @adriansun2999 Před 5 lety +1

    I love this; that you make real projects now days that are more "complete" and not just 'frontend', but I would like to see more front-end, please. E.g. you could explain how 'content: ""' works when people use it "before" and "after" when they do these seemingly magic stuff. How does it work? Looks like magic to me, and would like to know more about it.

  • @jwchavez
    @jwchavez Před 5 lety

    Great video as ever guys. Have a nice and successful 2019 , best wishes from México to both of you!

  • @usmanmaqbool7758
    @usmanmaqbool7758 Před 5 lety

    Thank you very much sir I really appreciate your work . Which helps me alot ❤.

  • @xx482
    @xx482 Před 5 lety

    Thanks for the tutorial. I was able to display only post data via jinja in html file and am unable to do a get request or put request , can you guide me or as you mentioned in the last of the video that you have already published a frontend video can you please point me that. Thanks
    Waiting for the response.

  • @UmerPKgrw
    @UmerPKgrw Před 3 lety +1

    Can someone please tell what was the purpose of the below commands running on python shell.
    Does it create objects as well or just created the db.
    From app import db
    Db.create_all()

  • @its_magnetic
    @its_magnetic Před 5 lety

    Thank you from India 🇮🇳 Sikkim.

  • @CaliMLD
    @CaliMLD Před 5 lety +1

    Hey Brad, you are a gift from the Web Dev Gods.

  • @takich9317
    @takich9317 Před 4 lety +37

    Hi, am getting an error, (TypeError: __init__() got an unexpected keyword argument 'strict') any advice

    • @denniskuria5945
      @denniskuria5945 Před 4 lety +7

      Got same errors too. I removed 'strict' and it worked.

    • @johnnysim1985
      @johnnysim1985 Před 4 lety

      Also getting this error, anyone know why?

    • @KushChoudhary
      @KushChoudhary Před 4 lety +42

      @@johnnysim1985 new version release. Schemas are always strict so no need.

    • @KushChoudhary
      @KushChoudhary Před 4 lety

      CzemBri ;p

    • @malamhari_
      @malamhari_ Před 4 lety +1

      @@KushChoudhary Thanks

  • @NikhilSandella
    @NikhilSandella Před 4 lety +3

    Thank you for this video. Please make a video on 'Flask as Rest API and Angular as the Front end.' Thumbs up.

  • @AyushGupta-ct2hi
    @AyushGupta-ct2hi Před 2 lety

    Thanks a lot for this, nicly explained but during delete part when I delete any product from the middle let say product number 3 in list of 5 products Is there a way to update its Product id?

  • @teclote
    @teclote Před 5 měsíci

    Outstanding, so clear and simple, thank you.

  • @nebiyebulan9242
    @nebiyebulan9242 Před 2 lety

    great video, I have a question. If I give an example, I have a user table and a vehicle table user and my vehicle table are one-to-many linked. When I get my user table, the vehicle's id comes. How do I get all the values ​​of the vehicle to be listed, not just the id?

  • @flat9safety
    @flat9safety Před 5 lety

    Just a note:
    jsonify does more than the simple conversion (if I'm not mistaken), it actually does some other prep steps to make it ready to be used as a response. For a simple conversion, you can use the built in module `json` ... json_string = json.dumps(som_python_dict)

  • @janneniemensivu475
    @janneniemensivu475 Před 5 lety +1

    Excellent tutorial. So far I have not figured out how to place classes in a separate file. Any suggestions on that?

  • @memodev
    @memodev Před 4 lety +1

    Hello! while passing the first product by postman this console throws me this error
    TypeError: 'Product' object is not iterable
    did that happen to anyone else? you can help me?

  • @davidw4918
    @davidw4918 Před 4 lety

    Thank you Brad, It is very good tutorial. The sample code works for me.

  • @pierre2338
    @pierre2338 Před 2 lety

    Really clear tutorial, thank you very much!

  • @user-hr6gh9us4s
    @user-hr6gh9us4s Před 2 lety

    Thanks from Japan.
    Your video is very useful to me.
    Thank you very much.

  • @barax9462
    @barax9462 Před 4 lety

    what happens exactly if i put method=[Delete] but within the handler i just updated a record instead of deleting...?? or generally the handler performing a task without considering the method. Beacuse to me it seems that the http-method is just a convention im confused.

  • @henriquepboueri
    @henriquepboueri Před 4 lety

    Thanks for sharing a little of knowledge. This makes the world a better place.

  • @Fedelios1
    @Fedelios1 Před 3 lety

    how can i build the front end now form formularies and everything?

  • @pankajambartani4934
    @pankajambartani4934 Před 4 lety

    Awesome, you're making our life easy..thanks!

  • @robsonsilv4.
    @robsonsilv4. Před 5 lety

    You read my mind! Awesome! Blueprint and RESTPlus is also a good next video(s)

  • @topdog91
    @topdog91 Před 5 lety

    Nice. Lots of online documentation is a bit out of date and will recommend flask-restful or flask-restplus. A better alternative is the stack you use, plus flask-classful. So easy and lightweight.

  • @MaNiMaBaLLa
    @MaNiMaBaLLa Před 5 lety

    Ohhh yeah, Flask tuts. Love it.

  • @JamesNjuguna1987
    @JamesNjuguna1987 Před 5 lety

    Hey Brad very nice video and very informative. How can I add swagger-ui so as to document my api endpoints
    ?

  • @canberkakartuna2599
    @canberkakartuna2599 Před 4 lety

    Thanks for this great content! Can you please help me how can you upload your files using Flask-SQLAlchemy? I know that using 'read()' function in request.files['input'] should work but for some reason it won't. I cannot figure out how we can properly upload files to sqlite database thanks.

  • @chethanbhat
    @chethanbhat Před 5 lety +4

    Thanks Brad ! Lots of Love

  • @kuthub1989
    @kuthub1989 Před 5 lety +1

    Brad, I'm a big fan of you. please do the full project-based course of a flask in udemy.

  • @reubenjosephcabrera8179

    just what I need :D thanks for this!

  • @reinhard_silaen
    @reinhard_silaen Před 3 lety +2

    If you found an error about strict or marshmallow. Install the packages following this version:
    marshmallow==3.0.0b6
    marshmallow-sqlalchemy==0.15.0

  • @aviralgangal8236
    @aviralgangal8236 Před 4 lety

    when i reopen the code and tried to run it gives error import flask ?

  • @philippegns
    @philippegns Před 3 lety

    Really good video for the basics, thanks !

  • @howards5205
    @howards5205 Před 5 lety +11

    Thank you for providing such great content. However, I believe many of us would like to see this project expanded further. Right now, as great this tutorial might be, it's not suitable to use for any real-world application. Some things I would like to see are: breaking the app.py into multiple files to separate out the models and routes, using token authentication, implementing model relationships, etc. I hope you please consider. Thank you.

  • @Ash-em5pm
    @Ash-em5pm Před 5 lety +26

    Is this some sort of magic?
    I swear I was reading flask documentation and now you post a video. Thank you so MUCH
    BTWBrad, what magic classes do you take,?

    • @TraversyMedia
      @TraversyMedia  Před 5 lety +18

      Come on, you know I can't tell you that. Nice try though :)

    • @wintereh4818
      @wintereh4818 Před 5 lety +2

      I was just looking into it too! Brad is in tune

    • @kuthub1989
      @kuthub1989 Před 5 lety +1

      me too.

  • @shameelibrahim7431
    @shameelibrahim7431 Před 5 lety +3

    Hi Brad, I've been following your channel for the past few months. I have learnt HTML and CSS as well as Python from your channel. I was forced to learn Java in my college as part our curriculum (which I find hard as a first time coder) and currently, we are going to make an Android app Although I find React Native to be really efficient, my professors, insist that I should make an app through Java. Can you include a crash course on Java and Android Studio. sorry if I'm asking too much. Your work is awesome as always

  • @manjujha456
    @manjujha456 Před 3 lety +1

    touch app.py file creation command not working in vs code terminal??

  • @EdniltonRauh
    @EdniltonRauh Před 5 lety

    Thanks Brad, your RestFull video is pretty cool. I would like to learn more about Restfull and MongoDb using Tuples, if you are thinking of a tutorial so I will wait for the bell to ring !!!

  • @edsouza6029
    @edsouza6029 Před 2 lety

    Thank you very much for this tutorial.
    product_schema = ProductSchema(strict=True) was throwing up an error for the flask server. So I omitted it and the program ran without any hiccups. I had to use the POSTMAN desktop app to request the API.
    Thank a lot again.
    Regards Ed

  • @fantastic1028
    @fantastic1028 Před 5 lety

    Wow, great tutorial! Thanks a lot!

  • @lawrencekatuva8735
    @lawrencekatuva8735 Před 4 lety

    self.view_functions[rule.endpoint](**req.view_args) am getting this internal server error please help

  • @devithuotkeo
    @devithuotkeo Před 4 lety

    does using post requests can be easy for hacker to inject random data to our website?

  • @donerlando9949
    @donerlando9949 Před rokem

    At 26:40, would it be all right to replace the two statements:
    result = products_schema.dump(all_products)
    return jsonify(result.data)
    with:
    products_schema.jsonify(all_products)
    ? I'm too much of a noob to understand the difference 🙈

  • @UncleNabs
    @UncleNabs Před 5 lety +4

    File "C:\Users\Engr\Documents\flask-api\traversy\app.py", line 47, in add_product
    name = request.json['name']
    TypeError: 'NoneType' object is not subscriptable
    after I try to make the same post request with postman. And I got the same error with the code from github so I wrote all the code correctly. Can anyone help with this?

  • @MistaT44
    @MistaT44 Před 5 lety +1

    Excellent video once again Brad!!! I would be grateful if you could do a Flask React app with deployment!

  • @michael.028
    @michael.028 Před 4 lety +4

    On the get all products route I had to remove .data from result in order to see my products. I was getting the error, " 'list' object has no attribute 'data' ".

    • @RyuKent
      @RyuKent Před 3 lety +3

      Use return jsonify(result) instead. You don't need .data

  • @xx482
    @xx482 Před 5 lety

    Thanks for the Video , you and your videos are reference guides to me when ever i am stuck up some where . I just want to know one thing once an api is built how do we show the same on UI , i just want few directions

  • @jaber4474
    @jaber4474 Před 5 lety

    very informative and needed thank you

  • @narudh
    @narudh Před 4 lety

    i don't understand why we need to use marshmallow? is it just to serialize the output of sqlalchemy queries and JSONify it?

  • @n3wtou
    @n3wtou Před 5 lety +2

    Awesome video. could you make a small video that integrates a flask backend and a react frontend. I would like to know how the data flows between both ends. More so how to send data from the frontend and receive it in the flask backend. Please if you do get a chance make a video on it. Thank you.

  • @ikezedev
    @ikezedev Před 5 lety

    Thanks man.... Always there for us 😍

  • @ryan.aquino
    @ryan.aquino Před 4 lety

    hi, i am getting error on delete. InvalidRequestError, Object '' is already attached to session '4' (this is '5')

  • @debojyotichatterjee4421

    In the get all products function what is the importance of the keyword "dump"??
    I tried
    return products_schema.jsonify(all_items)
    and it works fine. Can anyone help me understand?

  • @eugenesmykov3797
    @eugenesmykov3797 Před 5 lety

    I'm a simple man. When I see new video from Brad - put like on it

  • @VideoServicesLI
    @VideoServicesLI Před 5 lety

    Very Interesting - thank you!!