• Stars
    star
    1
  • Language
    Python
  • Created about 2 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Developing RESTful APIs with Python and Flask

Developing RESTful APIs with Python and Flask

Let's learn how to develop RESTful APIs with Python and Flask. We are going to use Flask and Python to develop a RESTful API. We will start by creating an endpoint that returns static data (dictionaries). After, we are going to create a class with two specializations and a few endpoints to insert and retrieve instances of these classes. Finally, will take a look on how to run the API on a Docker container.

Why Python?

Nowadays, choosing Python to develop applications is becoming a very popular choice. Python is one of the fastest-growing programming languages, having surpassed even Java on the number of questions asked on the platform.

Python Version

We recommend using the latest version of Python. Flask supports Python 3.7 and newer.

Why Flask?

When it comes to web development on Python, there are two frameworks that are widely used: Django and Flask. Django is older, more mature, and a little bit more popular. Even though Django is older and having a slightly bigger community, Flask has its strengths.

From the ground up, Flask was built with scalability and simplicity in mind. Flask applications are known for being lightweight, mainly when compared to their Django counterparts. Flask wonโ€™t make many decisions for us, such as what database to use or what template engine to choose. Lastly, Flask also has extensive documentation that address everything that developers need to start.

Bootstrapping a Flask Application

First and foremost, we will need to install some dependencies on our development machine. Basically, what we will need to install is Python 3, Pip (Python Package Index), and Flask. Fortunately, the process of installing these dependencies is quite simple.

Installing Python 3

After installing Python 3 on our machine, we can check that we have everything set up as expected by running the following command:

python --version # Python 3.6.2

Installing Pip

pip --version # pip 9.0.1 ... (python 3.X)

Installing Flask

Let's focus on installing it on our machine and testing to see if we can get a basic Flask application running. The first step is to use pip to install Flask: pip install Flask After installing the package, we will create a file called hello.py and add five lines of code to it.

    from flask import Flask

    app = Flask(__name__)

    @app.route("/")
    def index():
        return "<h1>Hello!</h1>"

    if __name__ == "__main__":
        from waitress import serve
        serve(app, host="127.0.0.1", port=8080)

Python Modules

Like other mainstream programming languages, Python also has the concept of modules to enable developers to organize source code according to subjects/functionalities.

Flask connect with Mysql

Flask connects to MySQL via the flask mysqldb connector. To install the package, use the following command: pip install flask_mysqldb

Setting Up Flask MySQL Database

Step 1: Connecting a Flask Application to a MySQL Database

    from flask import Flask,render_template, request
    from flask_mysqldb import MySQL

    app = Flask(__name__)

    app.config['MYSQL_HOST'] = 'localhost'
    app.config['MYSQL_USER'] = 'root'
    app.config['MYSQL_PASSWORD'] = ''
    app.config['MYSQL_DB'] = 'flask'

    mysql = MySQL(app)

Step 2: Configuring the MySQL Connection Cursor

    mysql = MySQL(app)

    #Creating a connection cursor
    cursor = mysql.connection.cursor()

    #Executing SQL Statements
    cursor.execute(''' CREATE TABLE table_name(field1, field2...) ''')
    cursor.execute(''' INSERT INTO table_name VALUES(v1,v2...) ''')
    cursor.execute(''' DELETE FROM table_name WHERE condition ''')

    #Saving the Actions performed on the DB
    mysql.connection.commit()

    #Closing the cursor
    cursor.close()

Step 3: Programming a Flask application

    from flask import Flask,render_template, request
    from flask_mysqldb import MySQL

    app = Flask(__name__)

    app.config['MYSQL_HOST'] = 'localhost'
    app.config['MYSQL_USER'] = 'root'
    app.config['MYSQL_PASSWORD'] = ''
    app.config['MYSQL_DB'] = 'flask'

    mysql = MySQL(app)

    @app.route('/form')
    def form():
        return render_template('form.html')

    @app.route('/login', methods = ['POST', 'GET'])
    def login():
        if request.method == 'GET':
            return "Login via the login Form"

        if request.method == 'POST':
            name = request.form['name']
            age = request.form['age']
            cursor = mysql.connection.cursor()
            cursor.execute(''' INSERT INTO info_table VALUES(%s,%s)''',(name,age))
            mysql.connection.commit()
            cursor.close()
            return f"Done!!"

    app.run(host='localhost', port=5000)

The form.html will be as follows:

<form action="/login" method="POST">
  <p>name <input type="text" name="name" /></p>
  <p>age <input type="integer" name="age" /></p>
  <p><input type="submit" value="Submit" /></p>
</form>

Step 4: Putting the Code into Action

  • Now start the server and navigate to โ€œ/formโ€
  • Enter the information and press the Submit button.
  • Letโ€™s take a look at it in the phpMyAdmin web interface now.

Finally! This concludes the Setting Up Flask MySQL Database Connection

More Repositories

1

zkteco

ZKTeco Package For Laravel. This package provides seamless integration with ZKTeco devices within Laravel applications, enabling communication with attendance devices such as fingerprint, face recognition, or RFID using UDP protocol.https://packagist.org/packages/jmrashed/zkteco
PHP
10
star
2

adibaicon

adibaIcon -Custome Icon Library
CSS
3
star
3

blood-donation-web-application-with-real-time-location-sharing

HTML
2
star
4

go-starter-kit

The Go Starter Kit is a foundational project for building a portfolio website using Go, structured to promote clean code and scalability. It employs the Gin web framework for routing and Viper for configuration management.
HTML
2
star
5

ecommerce

The E-commerce Toolkit for Laravel is a modular package providing essential features for building e-commerce websites. This package includes functionalities for managing product catalogs, carts, checkout systems, payment gateway integrations, and order management.
PHP
2
star
6

two-factor-auth

Laravel 2FA Authentication Package
PHP
2
star
7

phpmyadmin

phpmyadmin
PHP
2
star
8

laravel-automation-package

laravel-automation-package
PHP
1
star
9

laravel-installer

A complete web installer for Laravel applications, making the setup process simple and user-friendly.
PHP
1
star
10

rashed-games-javacript

Rashed's Game using HTML, CSS, and JavaScript
JavaScript
1
star
11

Django-Python-Starter-Kit-for-Beginner

Django was invented by Lawrence Journal-World in 2003, Initial release to the public was in July 2005. Latest version of Django is 4.0.3 (March 2022). This repository will help you, when you will get ready.
Python
1
star
12

face-detection-using-opencv

Face Detection using OpenCV
Python
1
star
13

ResponsiveLoginForm

JavaScript
1
star
14

jmrashed

About Md Rasheduzzaman
HTML
1
star
15

Webcam-capture-using-Html5-getUserMedia

Webcam capture using Html5 getUserMedia
JavaScript
1
star
16

desktop-application-using-phpnative-for-zkteco

desktop-application-using-phpnative-for-zkteco
PHP
1
star
17

News-Flutter-UI-Kit

News Flutter UI Kit
Dart
1
star
18

dart-practice-problem-solutions

Welcome to the Dart Practice Problem Solutions repository! This is a dedicated space for daily practice to learn Dart deeply. Our goal is to solve at least one problem each day for 100 days, continuously improving our Dart skills.
Dart
1
star
19

login-ui-react-native-app

This is a React Native application for implementing a login and signup UI/UX.
JavaScript
1
star
20

geolocation

The geolocation package will provide user location
PHP
1
star
21

Email-List-Cleaning-Tool-Using-PHP

Email List Cleaning Tool Using PHP
PHP
1
star
22

hospital-management-system

The Hospital Management System is a comprehensive software solution designed to facilitate efficient management and operations within a hospital or healthcare facility.
PHP
1
star
23

google-maps-polyline-draw

Draw polyline on google map using latitude and longitude coordinates
JavaScript
1
star
24

university-management-system-php

The University Management System is a web-based application developed using PHP. It provides a comprehensive solution for managing various aspects of a university, including student management, course management, faculty management, and administrative tasks.
PHP
1
star
25

Install-Redis-on-Windows

Install Redis on Windows
1
star
26

break-weakness-with-angular

break-weakness-with-angular
HTML
1
star
27

express-openapi-generator

express-openapi-generator
EJS
1
star