That's it! and in less than 60 lines of coding (included new lines)! Create DockerfileĪ Dockerfile is a text file to define a set of commands to create an image. To delete an existing item: methods=) def delete_item( id):ĭb.session.query(Item).filter_by(id=id).delete()
To update an existing item: methods=) def update_item( id):ĭb.session.query(Item).filter_by(id=id).update(ĭict(title=body, content=body))
To create a new item: methods=) def create_item():ĭb.session.add(Item(body, body)) To get all the items in the database, we define this function: methods=) def get_items():įor item in db.session.query(Item).all(): To retrieve a singleitem, we define this function: methods=) def get_item( id): These are the basic functions of every application. Now we need to implement our CRUD endpoints. This will create our databasetable automatically for us! db.create_all() Now a little bit of magic: with this line we let SQLAlchemy to synchronize with the Postgres database. Title = db.Column(db.String( 80), unique= True, nullable= False)Ĭontent = db.Column(db.String( 120), unique= True, nullable= False) Id = db.Column(db.Integer, primary_key= True) This will act as the primary key for our table. We’ll also add an auto-incremental Integer named id. We’ll create a class named Item with just title and content as properties.
Next, define the Flask app and how to run it: app = Flask(_name_)ĭefine an environment variable as a string and initialize the SQLAlchemy instance to handle the Postgres database: app.config = os.environ.get( 'DATABASE_URL') Let’s specify the libraries we’ll use: from flask import Flask, request, jsonify We will write our crud API app in about 50 lines of code! Flask-SQLAlchemy: Help generate SQL queries without writing them manuallyĪt the root level, create a file called app.py.psycopg2-binary: To create the connection with the Postgres Database.Then we can type the dependencies for our project: flask (If you have the Material Icon Theme, it will show a nice little Python icon. So create this file called "requirements.txt". The standard method in Python is to create a requirements.txt file and list our dependencies there. Now we’re ready to get started coding our Flask Crud API application with the help of GitHub Copilot! Create requirements.txtįirst of all, we need to define the dependent Python libraries for our application. If you use Visual Studio Code, you can type: code. Then, open this folder with your favorite IDE. Then, step into the folder: cd flask -crud -api If you use a terminal you can type: mkdir flask -crud -api You can create a folder in anyway that you prefer. In the next article we'll cover deploying a flask app to AWS. In this Article, we will create a simple CRUD API using a Flask Application, Docker, Postgres.
Welcome back on the Docker and AWS series by TinyStacks