Skip to content

A REST api made with Flask in which you can practice the methods: GET, POST, PUT and DELETE, of a tasks list application. This API will be connected to the postgres database.

aldomatus/flask-sqlachemy_postgresql_rest-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 

Repository files navigation


Header

A REST api made with Flask in which you can practice the methods: GET, POST, PUT and DELETE, of a tasks list application. This API will be connected to the postgres database.

Table of Contents
  1. About The Project
  2. Getting Started
  3. Usage
  4. Roadmap
  5. Contributing
  6. License
  7. Contact

About The Project

This project is made with the intention of teaching how to use Docker with Flask in the project we are going to take into account the following points:

  • Create the dockerfile that will have the necessary instructions to create a Python image that will later be converted into a single application.
  • Docker Compose allows you through YAML files to instruct the Docker Engine to perform tasks, programmatically. Here we will install the mysql image, declare the environment variables for both mysql and Flask, and also declare the volumes.
  • We will add the list of requirements in a requirements.txt file that will be executed automatically within the Dockerfile
  • Create a REST API with the methods: GET, POST, PUT and DELETE

Built With

This section should list any major frameworks that you built your project using. Leave any add-ons/plugins for the acknowledgements section. Here are a few examples.

Libraries

SQLAlchemy (Offers an ORM along with a Core)

The Python SQL Toolkit and Object Relational Mapper SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

Flask-Marshmallow (Serializer)

Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy.

To check your rest api

Insomnia

With their streamlined API client, you can quickly and easily send REST, SOAP, GraphQL, and GRPC requests directly within Insomnia. Link to visit insomnia website: - Link

Header

Postman

Postman is a collaboration platform for API development. Postman's features simplify each step of building an API and streamline collaboration so you can create better APIs—faster. Link to visit postman website: - Link

Header

Getting Started

Prerequisites

For this project you need to have the postgres database manager installed. If you have not installed it yet, you can install it by entering the following: link, you can work with its graphical interface or from the console, both ways will serve you. Let's create a database from the terminal:

  1. Once postgres is installed we can open a terminal and type the following code to access postgres
   sudo -u postgres psql
   
  1. once in postgres we can create a database for our application. You can decide the name of the database, in this case I will call it flaskpostgres
   create database flaskpostgres;
   
  1. You can check that your database is created with the following command, where all the databases that you have on your computer will appear, among them must be flaskpostgres
   \l
   

You will see something like this:

                                      List of databases
       Name        |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-------------------+----------+----------+-------------+-------------+-----------------------
 articulosclientes | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 flaskpostgres     | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 flaskprueba1      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 online_store      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 

Description of the REST API code

Click to see all the code
# Flask
from flask import Flask, request, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@localhost/flaskpostgres'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
ma = Marshmallow(app)


class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(70), unique=True)
    description = db.Column(db.String(100))

    def __init__(self, title, description):
        self.title = title
        self.description = description

db.create_all()

class TaskSchema(ma.Schema):
    class Meta:
        fields = ('id', 'title', 'description')


task_schema = TaskSchema()
tasks_schema = TaskSchema(many=True)

@app.route('/', methods=['GET'])
def home():
    return jsonify({'message': 'Welcome to my API'})

@app.route('/tasks', methods=['POST'])
def create_task():
    title = request.json['title']
    description = request.json['description']

    new_task= Task(title, description)

    db.session.add(new_task)
    db.session.commit()

    return task_schema.jsonify(new_task)

@app.route('/tasks', methods=['GET'])
def get_tasks():
    all_tasks = Task.query.all()
    result = tasks_schema.dump(all_tasks)
    return jsonify(result)

@app.route('/tasks/<id>', methods=['GET'])
def get_task(id):
    task = Task.query.get(id)
    return task_schema.jsonify(task)

@app.route('/tasks/<id>', methods=['PUT'])
def update_task(id):
    task = Task.query.get(id)
    title = request.json['title']
    description = request.json['description']

    task.title = title
    task.description = description

    db.session.commit()
    return task_schema.jsonify(task)

@app.route('/tasks/<id>', methods=['DELETE'])
def remove_task(id):
    task = Task.query.get(id)
    db.session.delete(task)
    db.session.commit()
    return task_schema.jsonify(task)
    

if __name__ == '__main__':
    app.run(debug=True, port=5000)

Describing the code

  1. first import libraries, name is just a convenient way to get the import name of the place the app is defined. Flask uses the import name to know where to look up resources, templates, static files, instance folder, etc. The application instance is an object of class Flask:
  
# Flask
from flask import Flask, request, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

app = Flask(__name__)
  1. Configure Flask by providing the PostgreSQL URI so that the app is able to connect to the database, through : app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://DB_USER:PASSWORD@HOST/DATABASE' where you have to replace all the parameters in capital letters (after postgresq://). Find out more on URI definition for PostgreSQL here.
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@localhost/flaskpostgres'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  1. We make the instances of SQLALchemy (to work with the database) and Marshmallow (For schemas and work with the database) of our application app
db = SQLAlchemy(app)
ma = Marshmallow(app)
  1. should include the definition of classes which define the models of your database tables. Such classes inherit from the class db.Model where db is your SQLAlchemy object.
class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(70), unique=True)
    description = db.Column(db.String(100))

    def __init__(self, title, description):
        self.title = title
        self.description = description
db.create_all()
  1. Generate marshmallow Schemas from your models using SQLAlchemySchema or SQLAlchemyAutoSchema.
class TaskSchema(ma.Schema):
    class Meta:
        fields = ('id', 'title', 'description')


task_schema = TaskSchema()
tasks_schema = TaskSchema(many=True)
  1. The client (such as a web browser) sends the request to the web server and the web server sends the request to the Flask application instance. The application instance needs to know what code to execute for each URL request, so the application instance keeps a function mapping relationship from URL to Python. The program that handles the relationship between URLs and functions is called routing.

Use what is provided by the application instance in Flask app.route The decorator registers the decorated function as a path:

A decorator (@) is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.

  
@app.route('/', methods=['GET'])
def home():
    return jsonify({'message': 'Welcome to my API'})
  1. The following decorated function uses the POST method. "Used to send HTML form data to the server. The data received by the POST method is not cached by the server."[1] The following decorated function uses the POST method. The most common method. A GET message is send, and the server returns data. In our example we receive with request the title and the description which we save in two variables that are sent to the Task class and then we make an instance that we will save inside new_task. Finally with session add we add to the database and save with commit, we return the new task with the help of task_schema.
  
@app.route('/tasks', methods=['POST'])
def create_task():
    title = request.json['title']
    description = request.json['description']

    new_task= Task(title, description)

    db.session.add(new_task)
    db.session.commit()

    return task_schema.jsonify(new_task)
  1. The following decorated function uses the GET method. The most common method. A GET message is send, and the server returns data. In our case, it will return the list of tasks to us. Hacemos uso de query.all() para traer toda la informacion de la base de datos. de Marshmallow utilizamos dump para esquematizar nuestros datos y retornamos un json con ayuda de jsonify para que nuestra api sea consumida
  
@app.route('/tasks', methods=['GET'])
def get_tasks():
    all_tasks = Task.query.all()
    result = tasks_schema.dump(all_tasks)
    return jsonify(result)
  1. Like the previous function, the next one uses the GET method, but as we can see, within the path /tasks/ we obtain an id , which our client will send us so that we can send the specific task information. In this case we use get to obtain a specific task and return with the help of a marshmello scheme
@app.route('/tasks/<id>', methods=['GET'])
def get_task(id):
    task = Task.query.get(id)
    return task_schema.jsonify(task)
6. GET method "replace all current representations of the target resource with uploaded content"[1], We obtain the id of the specific task with the id variable, with the help of the request we extract the information received from the client and then we save the information by doing session.commit() and we return the updated task.
  
@app.route('/tasks/<id>', methods=['PUT'])
def update_task(id):
    task = Task.query.get(id)
    title = request.json['title']
    description = request.json['description']

    task.title = title
    task.description = description

    db.session.commit()
    return task_schema.jsonify(task)
  7. DELETE: "Deletes all current representations of the target resource given by the URL"[1], to delete, we receive the id from the url, with query.get we identify what product it is and we delete the product with delete, finally we commit for the operation to proceed and we return the deleted task
# Delete products
@app.route('/tasks/<id>', methods=['DELETE'])
def remove_task(id):
  task = Task.query.get(id)
  db.session.delete(task)
  db.session.commit()
  return task_schema.jsonify(task)
  8. using the application instance run Method to start the embedded Flask web server:
  
if __name__=='__main__':
    app.run(debug=True, port=5000)

Installation

  1. To obtain my repository you must create a folder in a desired directory and within this folder open a terminal or use cmd in the case of windows.
  2. Clone the repo
    git remote add origin git@github.com:aldomatus/flask-docker_simple-rest-api.git
    
    
  3. Make the pull request from a branch called main
    git pull origin main --allow-unrelated-histories
    
    

git branch -m main is the command to rename the branch

  1. inside flask-sqlachemy_postgresql_rest-api we create a virtual environment to have our libraries together. we do it as follows

4.1. To download the library that allows us to create virtual environments

sudo apt-get install python3-venv

4.2. Create the virtual environment

python3 -m venv folder_name

4.3. Activate the virtual environment we go to the created folder and inside the terminal we write:

source bin / activate

  1. Once the virtual environment is activated, we return to the folder where the requirements.txt file is and to install our libraries we must type the following line. (if you are using python 3 you only must type python3)
python -m pip install -r requirements.txt

  1. then inside the console we write the following to indicate the file to flask.
export FLASK_APP = src/app.py

  1. we run the server with...
run flask

  1. If all goes well, our application should already be executing the app.py file with python using the postgres database, now we just have to check by entering the following link in our browser:

    http://localhost:5000/
    
  2. You should have a response like this:

    {"message": "Welcome to my API"}
    

Usage

With this base you can make any flask code, modify the API and adapt it to your projects.

Roadmap

See the open issues for a list of proposed features (and known issues).

Contributing

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

Distributed under the MIT License. See LICENSE for more information.

References

Contact

Aldo Matus - Linkedin Facebook

Project Link: Repository

About

A REST api made with Flask in which you can practice the methods: GET, POST, PUT and DELETE, of a tasks list application. This API will be connected to the postgres database.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published