A template for implementing REST API microservices with Flask and Python.
I haven't decided how much front end code will be included here. One thing at a time.
Just to get a taste of where this project is going, see this blog posting Python microservices with Flask.
I need to break out separate files.
I need to learn about blueprints.
I need to learn about request validation.
I need to work on the Docker set up.
I want better error handling.
I am tired of working on the Flask API so I am switching to a tiny Svelte app now to make it more fun to test. It will use the user database implemented in user_api.py. It will be in the client/ folder.
For development I usually run in a conda environment on the local machine. VSCODE is set up (see .vscode/launch.json) to launch hello_api.py for you on F5.
Command to set up and activate an environment:
$ conda create --name=flask --file=requirements
$ conda activate flask
My use case is so microscopic that deployment and scaling are non-issues for me, but normally I run the app in a Docker container using "waitress" as the server.
$ docker-compose build
$ docker run --rm -ti -p 5000:5000 flask:latest
When you open a browser http://localhost:5000, you should see a Hello, World message.
I use httpie from the command line to test, httpie gets installed in the "flask" environment so be sure you activate it.
By default VSCode runs hello_rest.py which implements a simple list of strings.
# POST items to the list
http "http://localhost:5000/list" item="apple"
http "http://localhost:5000/list" item="tanker truck"
http "http://localhost:5000/list" item="brick"
http "http://localhost:5000/list" item="water bottle"
# GET the list
http "http://localhost:5000/list"
# DELETE an item
http DELETE "http://localhost:5000/list" item="brick"
Creating the user database with SqlAlchemy did not apply UNIQUE constraint.
$ sqlite3 users.db
sqlite> CREATE TABLE user(id INTEGER PRIMARY KEY, username VARCHAR UNIQUE, password VARCHAR, role VARCHAR);
sqlite> .schema user
sqlite> .quit
Create a new repository and when you do, tell it you want to use this one as a template.
I started from my older project, flask_template.
I started with Python Flask Web Development but I don't have access to it right now. I wonder what Mr. Grinberg's Flask Mega-Tutorial is like. It's available as a book or as this blog. The Flask Mega-Tutorial Part I: Hello, World!
The book "Building REST APIs with Flask: Create Python Web Services with MySQL" promised REST but just delivered an app.
I own a copy of Mastering Flask Web Development and chapter 8 is "Building RESTful APIs".
Chapter 11 "Web API with Flask" from Building Web Apps with Python and Flask
I should look at Designing Microservices with Django but Django always seems like such a heavy lift for a starting point.