How to create a basic REST API?
Hello Everyone
Welcome to CloudAffaire and this is Debjeet.
So far, we have discussed what is REST API and how to interact with REST API using curl, Python or PowerShell. In this blog post, we will create our own basic REST API using Python’s Flask module.
How to create a basic REST API?
Prerequisite
- One Linux/Windows/MAC system
Step 1: Install Python and Pip in your system and activate a Python virtual environment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
## ----- ## Setup ## ----- ## Check if Python and pip installed python --version pip --version ## Install Python and Pip if not already installed # https://www.python.org/downloads/ # https://pip.pypa.io/en/stable/installation/ ## Install virtual environment pip install virtualenv ## Create a new virtual environment virtualenv myapp ## Activate virtual environment source myapp/bin/activate ## Install python Flask module pip install Flask |
Step 2: Create your 1st REST API using Python flask.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
## Create your 1st basic REST API ## create app.py cat <<'EOF'> myapp/app.py #!myapp/bin/python from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello, World!" if __name__ == '__main__': app.run(debug=True) EOF ## Start your REST API chmod a+x myapp/app.py myapp/app.py |
Our REST API initialized and is listing to http://127.0.0.1:500/
Next, we will make a REST API GET request to this endpoint.
Step 3: Interact with the basic REST API endpoint.
1 2 3 4 5 6 7 8 |
## Now from a separate command line call your REST API curl http://127.0.0.1:5000/ ## Returns ## Hello, World! ## Stop the REST API ## Press CTRL+C to quit |
Next, we will add different HTTP methods to our REST API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
## Update app.py cat <<'EOF'> myapp/app.py #!myapp/bin/python from flask import Flask, jsonify, abort, make_response, request app = Flask(__name__) employees = [ { "id": 1, "firstName": "Debjeet", "lastName": "Bhowmik", "email": "debjeettoni@gmail.com", "phone": "9748239852" }, { "id": 2, "firstName": "Chandrima", "lastName": "Koley", "email": "chandrima@gmail.com", "phone": "1111111111" } ] @app.route('/') def index(): return jsonify({"Message": "Welcome to REST API Version 1"}) @app.route('/api/v1.0/employees', methods=['GET']) def get_employees(): return jsonify({"employees": employees}) @app.route('/api/v1.0/employees/ def get_employee(id): employee = [employee for employee in employees if employee['id'] == id] if len(employee) == 0: abort(400) return jsonify({"employee": employee[0]}) @app.route('/api/v1.0/employees', methods=['POST']) def create_employee(): if not request.json or not 'firstName' or not 'lastName' or not 'email' or not 'phone' in request.json: abort(400) employee = { "id": employees[-1]["id"] + 1, "firstName": request.json.get("firstName", ""), "lastName": request.json.get("lastName", ""), "email": request.json.get("email", ""), "phone": request.json.get("phone", "") } employees.append(employee) return jsonify({"employees": employees}), 201 @app.route('/api/v1.0/employees/ def update_employee(id): employee = [employee for employee in employees if employee['id'] == id] if not request.json or not 'firstName' or not 'lastName' or not 'email' or not 'phone' in request.json: abort(400) employee[0]['firstName'] = request.json.get('firstName', employee[0]['firstName']) employee[0]['lastName'] = request.json.get('lastName', employee[0]['lastName']) employee[0]['email'] = request.json.get('email', employee[0]['email']) employee[0]['phone'] = request.json.get('phone', employee[0]['phone']) return jsonify({"employee": employee[0]}) @app.route('/api/v1.0/employees/ def delete_employee(id): employee = [employee for employee in employees if employee['id'] == id] if len(employee) == 0: abort(400) employees.remove(employee[0]) return jsonify({'result': True}) @app.errorhandler(400) def not_found(error): return make_response(jsonify({'Error': 'Bad Request'}), 400) if __name__ == '__main__': app.run(debug=True) EOF ## Start your REST API myapp/app.py |
Step 4: Test your REST API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
curl http://127.0.0.1:5000/ ## Returns ## { ## "Message": "Welcome to REST API Version 1" ## } curl --request GET \ http://127.0.0.1:5000//api/v1.0/employees ## Returns ## { ## "employees": [ ## { ## "email": "debjeettoni@gmail.com", ## "firstName": "Debjeet", ## "id": 1, ## "lastName": "Bhowmik", ## "phone": "9748239852" ## }, ## { ## "email": "chandrima@gmail.com", ## "firstName": "Chandrima", ## "id": 2, ## "lastName": "Koley", ## "phone": "1111111111" ## } ## ] ## } curl --request GET \ http://127.0.0.1:5000/api/v1.0/employees/1 ## Returns ## { ## "employee": { ## "email": "debjeettoni@gmail.com", ## "firstName": "Debjeet", ## "id": 1, ## "lastName": "Bhowmik", ## "phone": "9748239852" ## } ## } curl --request POST \ --data '{ "id": 3, "firstName": "Alex", "lastName": "Farguson", "email": "alex@gmail.com", "phone": "9876543210" }' \ --header "Accept:application/json" \ --header "Content-Type:application/json" \ http://127.0.0.1:5000/api/v1.0/employees ## Returns ## { ## "employees": [ ## { ## "email": "debjeettoni@gmail.com", ## "firstName": "Debjeet", ## "id": 1, ## "lastName": "Bhowmik", ## "phone": "9748239852" ## }, ## { ## "email": "chandrima@gmail.com", ## "firstName": "Chandrima", ## "id": 2, ## "lastName": "Koley", ## "phone": "1111111111" ## }, ## { ## "email": "alex@gmail.com", ## "firstName": "Alex", ## "id": 3, ## "lastName": "Farguson", ## "phone": "9876543210" ## } ## ] ## } curl --request PUT \ --data '{ "firstName": "Kunal", "lastName": "Sharma", "email": "kunal@gmail.com", "phone": "1234567899" }' \ --header "Accept:application/json" \ --header "Content-Type:application/json" \ http://127.0.0.1:5000/api/v1.0/employees/3 ## Returns ## { ## "employee": { ## "email": "kunal@gmail.com", ## "firstName": "Kunal", ## "id": 3, ## "lastName": "Sharma", ## "phone": "1234567899" ## } ## } curl --request DELETE \ http://127.0.0.1:5000/api/v1.0/employees/3 ## Returns ## { ## "result": true ## } |
Step 5: Clean up.
1 2 3 4 5 6 7 8 9 10 11 12 |
## -------- ## Clean up ## -------- ## Stop the REST API ## Press CTRL+C to quit ## Deactivate Python environment deactivate ## Remove environment rm -rf myapp |
Hope you have enjoyed this article. This was your first stepping stone to the world of REST API. If you want to learn more on Python Flask, please follow below official documentation.
https://flask.palletsprojects.com/en/2.0.x/
And here is a very good series on how to create a sample REST API application using Python Flask that uses persistent data store and authentication and other features.