flask crud api in python

To create a CRUD API using Flask in Python, follow these steps:

  1. Install Flask and SQLAlchemy:
main.py
pip install flask
pip install sqlalchemy
41 chars
3 lines
  1. Import necessary libraries:
main.py
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
124 chars
4 lines
  1. Initialize your Flask application:
main.py
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)
180 chars
6 lines
  1. Define your model:
main.py
class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    author = db.Column(db.String(100))
    genre = db.Column(db.String(100))
186 chars
6 lines
  1. Create a schema for your model:
main.py
class BookSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Book
80 chars
4 lines
  1. Create API endpoints for CRUD operations:
main.py
# Create a new book
@app.route('/books', methods=['POST'])
def add_book():
    title = request.json['title']
    author = request.json['author']
    genre = request.json['genre']
    new_book = Book(title=title, author=author, genre=genre)
    db.session.add(new_book)
    db.session.commit()
    book = Book.query.get(new_book.id)
    return book_schema.jsonify(book)

# Get all books
@app.route('/books', methods=['GET'])
def get_books():
    all_books = Book.query.all()
    return books_schema.jsonify(all_books)

# Get a single book
@app.route('/books/<id>', methods=['GET'])
def get_book(id):
    book = Book.query.get(id)
    return book_schema.jsonify(book)

# Update a book
@app.route('/books/<id>', methods=['PUT'])
def update_book(id):
    book = Book.query.get(id)
    title = request.json['title']
    author = request.json['author']
    genre = request.json['genre']
    book.title = title
    book.author = author
    book.genre = genre
    db.session.commit()
    return book_schema.jsonify(book)

# Delete a book
@app.route('/books/<id>', methods=['DELETE'])
def delete_book(id):
    book = Book.query.get(id)
    db.session.delete(book)
    db.session.commit()
    return '', 204
1198 chars
45 lines

That's it! You now have a Flask CRUD API for the Book model.

related categories

gistlibby LogSnag