An attempt to understand implmentation of a good REST API using Python.
I have used flask microframework to implement the REST API.
- Use Nouns in URI
- Let HTTP Verb define Action
- Pagination
- Searching/Filtering
- API Versioning
API performs CRUD operations on employees, authentication is implemented using JWT.
- Run MySQL database on port 3306.
- Export environment variables for the API
# Flask entry point
export FLASK_APP=run.py
# Database details
export DB_HOST=localhost
export DB_USER=app_user
export DB_PASSWORD=app@123
export DB_NAME=test
# Environment type
export FLASK_ENV=development
# Secret key for JWT encoding
export SECRET_KEY=abc#123@789
- Run Setup to create tables basis models
python setup.py
- Launch the API
flask run
- Signup -
curl -X POST -H "Content-Type: application/json" -d "@user.json" http://localhost:5000/api/auth/signup
- Login -
curl -X POST -H "Content-Type: application/json" -d "@user.json" http://localhost:5000/api/auth/login
A sample user request for authentication -
{
"email_id": "User007@gmail.com",
"password": "Pass@123"
}
- Get all employees and traverse with pages -
curl -X GET http://localhost:5000/api/employees
curl -X GET http://localhost:5000/api/employees?page=2
- Get employees filtered on employee's first_name -
curl -X GET http://localhost:5000/api/employees?first_name=John
- Get employee based on employee Id (emp_id) -
curl -X GET http://localhost:5000/api/employees/101
Addition of new employee can only be performed by authenticated user by passing JWT token received from login/signup.
curl -X POST -H "Content-Type: application/json" -H "x-access-token:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTY4NTU2MjUsImlhdCI6MTU5Njg1NTUwNSwic3ViIjozfQ.OiaQtzeGD8vj3LLxqTkaUrYj2VhKTsJSqKtumm9cpZs" -d "@emp.json" http://localhost:5000/api/employees
Updating of employee details can only be performed by authenticated user by passing JWT token received from login/signup.
curl -X PUT -H "Content-Type: application/json" -H "x-access-token:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTY4NTU2MjUsImlhdCI6MTU5Njg1NTUwNSwic3ViIjozfQ.OiaQtzeGD8vj3LLxqTkaUrYj2VhKTsJSqKtumm9cpZs" -d "@emp.json" http://localhost:5000/api/employees/101
Deletion of an employee can only be performed by authenticated user by passing JWT token received from login/signup.
curl -X POST -H "Content-Type: application/json" -H "x-access-token:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTY4NTU2MjUsImlhdCI6MTU5Njg1NTUwNSwic3ViIjozfQ.OiaQtzeGD8vj3LLxqTkaUrYj2VhKTsJSqKtumm9cpZs" http://localhost:5000/api/employees/101