This project shows one of the possible ways to implement RESTful API server.
There are implemented two models: User and Todo, one user has many todos.
Main libraries used:
- Flask-Migrate - for handling all database migrations.
- Flask-RESTful - restful API library.
- Flask-Script - provides support for writing external scripts.
- Flask-SQLAlchemy - adds support for SQLAlchemy ORM.
Project structure:
.
├── README.md
├── app.py
├── endpoints
│ ├── __init__.py
│ ├── todos
│ │ ├── __init__.py
│ │ ├── model.py
│ │ └── resource.py
│ └── users
│ ├── __init__.py
│ ├── model.py
│ └── resource.py
├── manage.py
├── requirements.txt
└── settings.py
- endpoints - holds all endpoints.
- app.py - flask application initialization.
- settings.py - all global app settings.
- manage.py - script for managing application (migrations, server execution, etc.)
- Clone repository.
- pip install requirements.txt
- Run following commands:
- python manage.py db init
- python manage.py db migrate
- python manage.py db upgrade
- Start server by running python manage.py runserver
POST http://127.0.0.1:5000/api/users
REQUEST
{
"name": "John John"
}
RESPONSE
{
"id": 1,
"name": "John John",
"todos": []
}
PUT http://127.0.0.1:5000/api/users/1
REQUEST
{
"name": "Smith Smith"
}
RESPONSE
{
"id": 1,
"name": "Smith Smith",
"todos": []
}
DELETE http://127.0.0.1:5000/api/users/1
RESPONSE
{
"id": 3,
"name": "Tom Tom",
"todos": []
}
GET http://127.0.0.1:5000/api/users
RESPONSE
{
"count": 2,
"users": [
{
"id": 1,
"name": "John John",
"todos": [
{
"id": 1,
"name": "First task",
"description": "First task description"
},
{
"id": 2,
"name": "Second task",
"description": "Second task description"
}
]
},
{
"id": 2,
"name": "Smith Smith",
"todos": []
}
]
}
GET http://127.0.0.1:5000/api/users/2
{
"id": 2,
"name": "Smith Smith",
"todos": []
}
GET http://127.0.0.1:5000/api/users?name=John John
{
"count": 1,
"users": [
{
"id": 1,
"name": "John John",
"todos": [
{
"id": 1,
"name": "First task",
"description": "First task description"
},
{
"id": 2,
"name": "Second task",
"description": "Second task description"
}
]
}
]
}
GET http://127.0.0.1:5000/api/users?limit=1&offset=1
{
"count": 1,
"users": [
{
"id": 2,
"name": "Smith Smith",
"todos": []
}
]
}
Todo endpoint is similar to Users endpoint.