Flask is actually really a powerful tool for making an API. In the video below, you would see how quickly I am building an API, that does four really simple functions.
The functions are – saying “Hello”, multiplying a number by itself 2 times (e.g. cubing a number), concatenating 2 strings and just returning twice any given string. Nothing fancy, but if this is the first time you are seeing Flask, API and Python I hope it would be useful!
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 |
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/api/testapi', methods=['POST']) def testapi(): data = request.get_json() print(f'{data}{data}') return f'{data}{data}' @app.route('/api/greet', methods=['POST']) def greet(): data = request.get_json() if 'name' not in data: return jsonify({'error':'Required - name!'}), 400 name = data['name'] greeting = f"Hello, there - {name}!" return jsonify({'message':greeting}) @app.route('/api/cube', methods=['POST']) def cube(): data = request.get_json() #print("\nMultiplying 3 times the same value!") if 'number' not in data: return jsonify({'error':'Required - number!'}), 400 number = data['number'] result = number ** 3 return jsonify({'result': result}) @app.route('/api/concat', methods=['POST']) def concat(): data = request.get_json() if ('string1' not in data) or ('string2' not in data): return jsonify({'error':'Required - string1 and string2!'}), 400 string1 = data['string1'] string2 = data['string2'] result = string1 + string2 return jsonify({'result': result}) if __name__ == '__main__': app.run(debug=True) |
Additionally, there are 3 tests for the “cube” function:
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 |
import unittest import json from app import app class TestApp(unittest.TestCase): def setUp(self): self.app = app.test_client() self.app.testing = True def test_cube_endpoint(self): data = {"number": 5} response = self.app.post('/api/cube', json=data) result = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(result['result'], 125) def test_cube_negative_number(self): data = {"number": -3} response = self.app.post('/api/cube', json=data) result = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(result['result'], -27) def test_cube_missing_number(self): data = {} response = self.app.post('/api/cube', json=data) result = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertIn('error', result) if __name__ == '__main__': unittest.main() |
To run the tests, enter in the terminal python test_app.py.
To run the API, enter in the terminal python app.py.
And I hope you have enjoyed the video! 🙂