A simple User RESTFUL API built using Flask Framework (http://flask.pocoo.org/) and Sqlalchemy (http://www.sqlalchemy.org/)
Python 2.7.x
-
Create a virtual with:
mkvirtualenv flaskapi workon flaskapi
-
Install requirements file:
pip install -r requirements.txt
-
Run unit test suite:
python manage.py test
-
Create database:
python manage.py syncdb
-
Run app:
python manage.py runserver
The main goal is desing and built a RestFull API that handles user registration and login for a new service (let's say a music service but could be anything). The API format will be JSON. The first thing that we must do is define a root url: ::
http://[hostname]/mymusic/api/v1.0/
After that we will define the User Resource urls that will allows to create, query, update, delete an user.
POST request to create an user: ::
curl -X POST localhost:5000/mymusic/api/v1.0/users/ -H "Content-Type: application/json" \
-d '{"username": "maigfrga", "email": "maigfrga@gmail.com", \
"last_name": "franco", "first_name": "manuel"}'
This request will return a json with the user information, access_token included: ::
{
"user": {
"access_token": "dda568fe6781259a1f9b910c6704b4da",
"email": "maigfrga@gmail.com",
"first_name": "manuel",
"id": 1,
"last_name": "franco",
"username": "maigfrga"
}
}
GET, PUT, DELETE request requires authentication, the API expects two headers api_access_token and api_username the next example will return user information, authentication is required: ::
curl localhost:5000/mymusic/api/v1.0/users/ -H "api_access_token: dda568fe6781259a1f9b910c6704b4da" \
-H "api_username: maigfrga"
This call will return the user data: ::
{
"access_token": "dda568fe6781259a1f9b910c6704b4da",
"email": "maigfrga@gmail.com",
"first_name": "manuel",
"id": 1,
"last_name": "franco",
"username": "maigfrga"
}
Perform a PUT request will update the user resource: ::
curl -X PUT localhost:5000/mymusic/api/v1.0/users/ -H "Content-Type: application/json" \
-H "api_access_token: dda568fe6781259a1f9b910c6704b4da" \
-H "api_username: maigfrga" -d '{"last_name": "last name modified"}'
Perform a DELETE request will delete the user resource: ::
curl -X DELETE localhost:5000/mymusic/api/v1.0/users/ \
-H "api_access_token: dda568fe6781259a1f9b910c6704b4da" \
-H "api_username: maigfrga"
Designing a RESTful API with Python and Flask
argparse — Parser for command-line options, arguments and sub-commands