NYU DevOps lab showing a very simple REST API all on one Python module app.py
This lab demonstrates how to create a simple REST service using Python Flask and SQLite. The resource model is persistenced using SQLAlchemy to keep the application simple. SQLAlchemy is an Object Relational Mapper (ORM) that will allow you to work with classes instead of database records.
This projects purpose is to show the correct API and return codes that should be used for a REST API. Everything is contained ina single
The easiest way to use this lab is with Vagrant and VirtualBox. if you don't have this software the first step is down download and install it.
Download VirtualBox
Download Vagrant
Then all you have to do is clone this repo and invoke vagrant:
git clone https://github.com/nyu-devops/lab-flask-rest.git
cd lab-flask-rest
vagrant up
vagrant ssh
cd /vagrant
FLASK_APP=service:app flask run -h 0.0.0.0
You can also automatically set the environment variable FLASK_APP using a .env
file.
There is an example in this repo called .env-example
that you can simply copy.
cp .env .env-example
The .env
file will be loaded when you do flask run
so that you don't have to specify
any environment variables.
If you have Python 3 installed on your computer you can make a virtual environment and run the code locally with:
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
FLASK_APP=service:app flask run
Run the tests using nose
nosetests
Nose is configured to automatically include the flags --with-spec --spec-color
so that red-green-refactor is meaningful. If you are in a command shell that supports colors, passing tests will be green while failing tests will be red. It also has --with-coverage
specified so that code coverage is included in the tests.
The Code Coverage tool runs with nosetests
so to see how well your test cases exercise your code just run the report:
coverage report -m
This is particularly useful because it reports the line numbers for the code that is not covered so that you can write more test cases.
To run the service use flask run
(Press Ctrl+C to exit):
FLASK_APP=service:app flask run -h 0.0.0.0
You must pass the parameters -h 0.0.0.0
to have it listed on all network adapters to that the post can be forwarded by vagrant
to your host computer so that you can open the web page in a local browser at: http://localhost:5000
When you are done, you can exit and shut down the vm with:
exit
vagrant halt
If the VM is no longer needed you can remove it with:
vagrant destroy
This repo is part of the DevOps course CSCI-GA.2820-001/002 at NYU taught by John Rofrano.