blog image

API building using Flask

pip install flask_restful

CRUD Operation 

#models.py
from . import db
from datetime import datetime

class School(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    location = db.Column(db.Text, nullable=False)
    created_at=db.Column(db.DateTime,default=datetime.now())

    def serialize(self):
        return {
            'id': self.id,
            'name': self.name,
            'location': self.location,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else ""
        }



#api
from flask_restful import Api,Resource
from . models import School
from . import db
from flask import jsonify,request


class SchoolResourceGetPost(Resource):
    def get(self):
        schools=School.query.all()
        serialized_schools = [school.serialize() for school in schools]
        return jsonify(serialized_schools)

    def post(self):
        #name=request.form.get('name')
        #name=request.json['name']
        #data=request.get_json()

        form_data=request.form
        name=form_data.get('name')
        location=form_data.get('location')
        if not name or not location:
            return {"message":"Name and location are required"},400
        school=School(name=name,location=location)
        db.session.add(school)
        db.session.commit()
        return {"message":"Data added succesfully","data":school.serialize()},201

class SchoolResourceRetrivePutDelete(Resource):
    def get(self,id):
        school=School.query.get(id)
        if school is None:
            return {"message":"School doesnot exist"},400
        serialized_school = school.serialize()
        return jsonify(serialized_school)

    def put(self,id):
        form_data=request.form
        name=form_data.get('name')
        location=form_data.get('location')
        if not name or not location:
            return {"message":"Name and location are required"},400
        school=School.query.get(id)
        if school is None:
            return {"message":"School doesnot exist"},400
        school.name=name
        school.location=location
        db.session.add(school)
        db.session.commit()
        return {"message":"Data updated succesfully","data":school.serialize()},200

    def delete(self,id):
        school=School.query.get(id)
        if school is None:
            return {"message":"School doesnot exist"},400
        db.session.delete(school)
        db.session.commit()
        return {"message":"Data deleted successfully"},200

 


About author

author image

Amrit Panta

Python developer, content writer



3 Comments

Amanda Martines 5 days ago

Exercitation photo booth stumptown tote bag Banksy, elit small batch freegan sed. Craft beer elit seitan exercitation, photo booth et 8-bit kale chips proident chillwave deep v laborum. Aliquip veniam delectus, Marfa eiusmod Pinterest in do umami readymade swag. Selfies iPhone Kickstarter, drinking vinegar jean.

Reply

Baltej Singh 5 days ago

Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Marie Johnson 5 days ago

Kickstarter seitan retro. Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Leave a Reply

Scroll to Top