AllFlaskProjectsPython

Flask API Part 1: Setup Python Flask | Create Json API Using Flask | Python Flask Project

Flask API Part 1: Setup Python Flask | Create Json API Using Flask | Python Flask Project SoftwareTechIT

What will we Learn In This Video:-

Learn Python Flask

Learn Database MySQL Connection Using Flask

Learn flask Web

Learn Flask Table And Insert Data In Database

Generate URLS

Get Responce And Return The Data

HTTP Methods ( GET / POST / PATCH / DELETE / PUT)

Operations On Database Using flask Python

CREATE / SELECT / UPADATE / DELETE

Return Json Data RestAPI

🌎 Website :- https://softwaretechit.com

📰 Blog:- https://blog.softwaretechit.com

🛒 Shopping :- https://shop.softwaretechit.com

📑 Product Review :- https://productsellermarket.softwaretechit.com

Code In This Video

Setup Flask App For Project

Python Flask is a micro web framework for Python that allows developers to easily create and deploy web applications. To set up a Python Flask project, the following steps should be taken:

  1. Install Python: In order to use Flask, you must have Python installed on your computer. You can download the latest version of Python from the official website.
  2. Create a new project directory: Create a new folder on your computer where you will store your Flask project.
  3. Install Flask: Use the pip package manager to install Flask. Open a command prompt or terminal window and type “pip install Flask” to install Flask.
  4. Create a new Python file: Inside your project directory, create a new file called “app.py” or “main.py”. This file will contain the main code for your Flask application.
  5. Add the Flask code: In the “app.py” or “main.py” file, add the following code to import Flask and create a new Flask application:
from flask import Flask
app = Flask(__name__)

Create a route: A route is the URL path that a user will visit to access your application. To create a route, use the “@app.route” decorator and specify the path. For example:

@app.route('/')
def index():
    return 'Hello, World!'
  1. Run the application: To run the application, use the “flask run” command in the command prompt or terminal window. Your application will be accessible at http://localhost:5000/.

With these steps, you have successfully set up a Python Flask project and can begin building and deploying your web application.

  1. Install Flask by running pip install flask in your command line.
  2. Create a new directory for your project and navigate to it.
  3. Create a file called app.py in your project directory and open it in your text editor.
  4. In the app.py file, import Flask and create a new Flask application by running app = Flask(__name__).
  5. Define routes for your API using the @app.route decorator. For example, you might create a route for /products that returns a list of products in JSON format.
  6. Create a function to handle the logic for each route. For example, you might create a function called get_products() that queries a database for a list of products and returns them in JSON format.
  7. Add the logic function to the route using the .route decorator.
  8. Finally, run the application using if __name__ == '__main__': app.run(debug=True)

This is just a basic setup. You can add more functionality like adding a json or xml parser, or security features like JWT, or adding a database for storing the data, and more features according to your requirement.

lets create api in the flask python for our ecommerce project

App.py

from flask import Flask,request,redirect,jsonify,render_template,flash,url_for
from flask_cors import cross_origin
from werkzeug.utils import secure_filename
import os
import urllib.request
import products
import cart
import users
import uploadfiles 


pobj=products.Products()
cobj=cart.CartProduct()
uobj=users.Users()
#initiolize app to flask
app=Flask(__name__)
# app.config['UPLOAD_FOLDER']=UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH']=16*1024*1024

#create home Route 
@app.route('/')
def index():
    return render_template("index.html")

@app.route('/product', methods=['GET','POST'])
@cross_origin(origins="*",headers=['content-type'])
def productList():
    if(request.method=='GET'):
        if(request.args):
            limit=request.args.get('limit',type=int)
        else:
            limit=15
        data=pobj.getProducts(limit)         #we have to add responce code like 200 for succussess 400 error 
        if len(data):
            responce = jsonify({
                "result":data,
                "status":200
            })
        else:
            responce = jsonify({
                "result":data,
                "status":400
            })
        return responce
    elif(request.method=='POST'):
        data=request.json
        aData=pobj.createProduct(data['data'])
        if aData==200:
            responce = jsonify({
                "result":aData,
                "status":200,
                "massage":"created successfully"
                
            })
        else:
            responce = jsonify({
                "result":aData,
                "status":400,
                "massage":"faild to create"
            })
        return responce
#we are update data end delete the product using this url
@app.route('/product/<int:pid>',methods=['GET','PUT','DELETE','PATCH','OPTIONS'])
@cross_origin(origins="*", headers=['content-type'])
def productchenge(pid):
    if(request.method=='PUT'):
        data=request.json
        aData=pobj.updateProduct(data,pid)
        if(aData==200):
            responce=jsonify({
                "result":aData,
                "status":200,
                "massage":"update Successfully"
            })
        else:
            responce=jsonify({
                "result":aData,
                "status":400,
                "massage":"Faild to update"
            })
        return responce
    elif(request.method=='DELETE'):
        aData=pobj.deleteProduct(pid)
        if(aData==200):
            responce=jsonify({
                "result":aData,
                "status":200,
                "massage":"DELETE Successfully"
            })
        else:
            responce=jsonify({
                "result":aData,
                "status":400,
                "massage":"Faild to DELETE"
            })
        return responce
    elif(request.method=='PATCH'):
        return "Patch http method"
    elif(request.method=='GET'):
        data=pobj.getSingleProduct(pid)         #we have to add responce code like 200 for succussess 400 error 
        if len(data):
            responce = jsonify({
                "result":data,
                "status":200
            })
        else:
            responce = jsonify({
                "result":data,
                "status":400
            })
        return responce
    else:
        return "options http method"

#we are update data end delete the cart using this url
@app.route('/cart',methods=['GET','POST','OPTIONS'])
@cross_origin(origins="*", headers=['Content-Type'])
def addCart():
    if(request.method=='GET'):
       
        cdata=cobj.getCartProduct()
        if len(cdata):
            responce = jsonify({
                "result":cdata,
                "status":200
            })
        else:
            responce = jsonify({
                "result":cdata,
                "status":400
            })
        return responce
    elif(request.method=='POST'):
        data=request.json
        cData=cobj.createCartService(data['data'])
        if cData==200:
            responce = jsonify({
                "result":cData,
                "status":200,
                "massage":"created successfully"
                
            })
        else:
            responce = jsonify({
                "result":cData,
                "status":400,
                "massage":"faild to create"
            })
        return responce
    else:
        return "options http method"
        
@app.route('/cart/<int:cid>', methods=['GET','POST','DELETE'])
@cross_origin(origins="*", headers=['Content-Type'])
def delCart(cid):
    if(request.method=='DELETE'):
        # id=request.args.get('id', type=int)
        cData=cobj.delCartItem(cid)
        if(cData==200):
            responce=jsonify({
                "result":cData,
                "status":200,
                "massage":"DELETE Successfully"
            })
        else:
            responce=jsonify({
                "result":cData,
                "status":400,
                "massage":"Faild to DELETE"
            })
        return responce

@app.route('/users', methods=['GET','POST'])
@cross_origin(origins="*", headers=['Content-Type'])
def getUser():
    udata=uobj.getUsers()
    if udata!="":
        responce = jsonify({
            "result":udata,
            "status":200,
            "massage":"get successfully"
            
        })
    else:
        responce = jsonify({
            "result":udata,
            "status":400,
            "massage":"faild to get"
        })
    return responce

@app.route("/upload",methods=["POST"])
@cross_origin(origins="*",headers=["Content-Type"])
def upload_files():
    if 'file' not in request.files:
       return jsonify("no file part")
    file=request.files['file']
    if file.filename=='':
        return jsonify("no image selected for uploading ")
    getic=uploadfiles.files_image(file)
    if(getic==200):
        return jsonify("File Upload successfully")
    elif(getic==400):
        return jsonify("file not uploded")

    

@app.route("/img",methods=['GET'])
@cross_origin(origins="*",headers=['Content-Type'])
def imgform():
   return render_template("uploaddemo.html")

#we have to debug app for erros & it will check name if its main
if __name__=='__main__':
    app.run(debug=True)

This code uses the Flask framework to create a web application with several routes for handling different requests. The app is initialized with the Flask module and several other modules such as request, redirect, jsonify, render_template, and flash are imported. Additionally, three classes, Products, CartProduct and Users, are imported from separate modules to handle specific actions such as getting products, managing the cart and managing users.

The code creates routes for the home page, product listing, and product management. The home page route is defined as ‘/’ and it renders the index.html template. The product listing route is defined as ‘/product’ and it handles both GET and POST requests. It returns a list of products when a GET request is made and it creates a new product when a POST request is made. The product management route is defined as ‘/product/int:pid‘ and it handles different types of requests such as GET, PUT, DELETE, PATCH and OPTIONS. The route is used to update, delete and get a single product.

The code also includes a route for managing the cart, ‘/cart’, which handles GET, POST and OPTIONS requests. It allows users to add items to their cart and view the items in their cart. The code also uses the Flask-Cors module to handle cross-origin resource sharing and the Werkzeug module to handle file uploads. Overall, this code provides a basic structure for a web application with multiple routes for handling different types of requests.

Leave a ReplyCancel reply

Exit mobile version