[Python] Quickly create an API with Flask

what's this

There are times when you want to quickly create a small API while using a DB. In that case, Flask is convenient. Basically, you can create an API just by fleshing out the following code.

Caution

In my opinion, if you have a medium-sized project, add flask- * later, or use a lot of DB, you should use a framework such as Django. If you plan to move to another framework later, use that one.

code

The API that provides CRD for Model is shown below. (Update will be implemented later if you feel like it)

# coding: utf-8
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@localhost/postgres'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)


# Model
class Model(db.Model):
    __tablename__ = 'models'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)

    def to_dict(self):
        return dict(
            id=self.id,
            name=self.name
        )

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Model {}>'.format(self.name)


@app.route("/api/v1/model/<id>", methods=['DELETE'])
def api_v1_model_id(id):
    if request.method == 'DELETE':
        d = Model.query.get(id)
        db.session.delete(d)
        db.session.commit()
        return '', 204


@app.route("/api/v1/models", methods=['GET', 'POST'])
def api_v1_models():
    if request.method == 'POST':
        name = request.json['name']
        d = Model(name)
        db.session.add(d)
        db.session.commit()
        return jsonify(d.to_dict()), 201
    if request.method == 'GET':
        ls = Model.query.all()
        ls = [l.to_dict() for l in ls]
        return jsonify(ls), 200


if __name__ == "__main__":
    db.drop_all()
    db.create_all()
    app.run(host='0.0.0.0', port=3001)

Recommended Posts

[Python] Quickly create an API with Flask
Create an API server quickly with Python + Falcon
Quickly create an excel file with Python #python
Create an API with Django
Create an animated GIF local server with Python + Flask
Create Awaitable with Python / C API
Create an Excel file with Python3
Create API with Python, lambda, API Gateway quickly using AWS SAM
Create an English word app with python
Programming with Python Flask
Create an app that guesses students with python
Create an image composition app with Flask + Pillow
Create an image with characters in python (Japanese)
Use Trello API with python
Create an environment with virtualenv
Use Twitter API with Python
Create 3d gif with python3
API with Flask + uWSGI + Nginx
Creating an egg with python
Web API with Python + Falcon
Call the API with python3.
Web application with Python + Flask ② ③
Use subsonic API with python3
Create a directory with python
Web application with Python + Flask ④
[LINE Messaging API] Create parrot return BOT with Python
Try hitting the Twitter API quickly and easily with Python
Quickly take a query string with API Gateway-> Lambda (Python)
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
[Python Kivy] How to create an exe file with pyinstaller
Cut out an image with python
SNS Python basics made with Flask
[AWS] Create API with API Gateway + Lambda
Create folders from '01' to '12' with python
Persist Flask API server with forever
[Python] Use Basic/Digest authentication with Flask
Quine Post with Qiita API (Python)
Create a virtual environment with Python!
I sent an SMS with Python
Create Gmail in Python without API
[python] Read information with Redmine API
Create API using hug with mod_wsgi
Create an age group with pandas
Quickly implement REST API in Python
Draw an illustration with Python + OpenCV
[Python] Send an email with outlook
Application development with Docker + Python + Flask
[Python] Create API to send Gmail
Create an alias for Route53 to CloudFront with the AWS API
How to create a heatmap with an arbitrary domain in Python
[LINE Messaging API] Create a BOT that connects with someone with Python
[For Python] Quickly create an upload file to AWS Lambda Layer
Create an application that just searches using the Google Custom Search API with Python 3.3.1 in Bottle
Collecting information from Twitter with Python (Twitter API)
Create an application by classifying with Pygame
[Python] Building an environment with Anaconda [Mac]
Create a Python function decorator with Class
Create wordcloud from your tweet with python3
Build a blockchain with Python ① Create a class
Create an image processing viewer with PySimpleGUI
Create a dummy image with Python + PIL.