Day 66 - Cafe API Project & RESTful route


Posted by pei_______ on 2022-06-19

learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022


Flask - jsonify
POSTman - Documentation
My Cafe API - Documentation


00. Set & Connect with Database

from flask import Flask, jsonify, render_template, request
from flask_sqlalchemy import SQLAlchemy
from random import choice

app = Flask(__name__)

##Connect to Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


##Cafe TABLE Configuration
class Cafe(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), unique=True, nullable=False)
    map_url = db.Column(db.String(500), nullable=False)
    img_url = db.Column(db.String(500), nullable=False)
    location = db.Column(db.String(250), nullable=False)
    seats = db.Column(db.String(250), nullable=False)
    has_toilet = db.Column(db.Boolean, nullable=False)
    has_wifi = db.Column(db.Boolean, nullable=False)
    has_sockets = db.Column(db.Boolean, nullable=False)
    can_take_calls = db.Column(db.Boolean, nullable=False)
    coffee_price = db.Column(db.String(250), nullable=True)

    def to_dic(self):
        dictionary = {}
        for column in self.__table__.columns:
            # Create a new dictionary entry;
            # where the key is the name of the column
            # and the value is the value of the column
            dictionary[column.name] = getattr(self, column.name)
        return dictionary


@app.route("/")
def home():
    return render_template("index.html")

01. HTTP GET - Read Record

ALL_CAFES = db.session.query(Cafe).all()


@app.route("/random")
def random():
    cafe = choice(ALL_CAFES)
    return jsonify(cafe=cafe.to_dic())


@app.route("/all")
def get_all():
    cafes_list = [cafe.to_dic() for cafe in ALL_CAFES]
    return jsonify(cafes=cafes_list)


@app.route("/search", methods=["POST", "GET"])
def search():
    searching_loc = request.args.get('loc')
    loc_list = [cafe.location for cafe in ALL_CAFES]
    if searching_loc in loc_list:
        matched_cafes = Cafe.query.filter_by(location=searching_loc).all()
        matched_list = [cafe.to_dic() for cafe in matched_cafes]
        return jsonify(cafe=matched_list)
    else:
        return jsonify(error={
            "Not Found": "Sorry, we don't have a cafe in this location."})

02. HTTP POST - Create Record

@app.route("/add", methods=["POST"])
def add():
    new_cafe = Cafe(
        id=request.form.get('id'),
        name=request.form.get('name'),
        map_url=request.form.get('map_url'),
        img_url=request.form.get('img_url'),
        location=request.form.get('location'),
        seats=request.form.get('seats'),
        has_toilet=bool(request.form.get('has_toilet')),
        has_wifi=bool(request.form.get('has_wifi')),
        has_sockets=bool(request.form.get('has_sockets')),
        can_take_calls=bool(request.form.get('can_take_calls')),
        coffee_price=request.form.get('coffee_price')
    )
    db.session.add(new_cafe)
    db.session.commit()
    return jsonify(response={
        "success": "Successfully added the new cafe."
    })

03. HTTP PUT/PATCH - Update Record

@app.route("/update-price/<cafe_id>")
def update_price(cafe_id):
    cafe_to_update = Cafe.query.get(cafe_id)
    try:
        cafe_to_update.coffee_price = request.args.get('new_price')
        db.session.commit()

    except AttributeError:
        return jsonify(error={
            "Not Found": "Sorry a cafe with that id was not found."
        })
    else:
        return jsonify(response={
            "success": "Successfully update the price."
        })

04. HTTP DELETE - Delete Record

@app.route('/report-closed/<cafe_id>')
def delete(cafe_id):
    cafe_to_delete = Cafe.query.get(cafe_id)
    get_api_key = request.args.get('api-key')
    if get_api_key == "secret":
        try:
            db.session.delete(cafe_to_delete)
            db.session.commit()
        except:
            return jsonify(error={
                "Not Found": "Sorry a cafe with that id was not found."
            })
        else:
            return jsonify(response={
                "success": "Successfully delete the cafe."
            })
    else:
        return jsonify(
            error="Sorry, that's not allowed. Make sure you have the correct api_key.")


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

#Python #課堂筆記 #100 Days of Code







Related Posts

每日心得筆記 2020-07-03(五)

每日心得筆記 2020-07-03(五)

什麼是法定貨幣?什麼是虛擬貨幣?什麼是安定幣?

什麼是法定貨幣?什麼是虛擬貨幣?什麼是安定幣?

day_02: 我不會寫函式

day_02: 我不會寫函式


Comments