1from flask import Flask
2from flask_restful import Resource, Api
3
4app = Flask(__name__)
5api = Api(app)
6
7class HelloWorld(Resource):
8 def get(self):
9 return {'hello': 'world'}
10
11api.add_resource(HelloWorld, '/')
12
13if __name__ == '__main__':
14 app.run(debug=True)
15
1""" This website does pretty-good explanation with a working example
2
3 https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask
4"""
1
2@app.route('/api/v1/users', methods=['GET'])
3def get_users():
4 users = [ user.json() for user in User.query.all() ]
5 return jsonify({'users': users })
6
7@app.route('/api/v1/users/<id>', methods=['GET'])
8def get_user(id):
9 user = User.query.filter_by(id=id).first()
10 if user is None:
11 return jsonify({'message': 'User does not exists'}), 404
12
13 return jsonify({'user': user.json() })
14
1from flask import Flask
2from flask_restful import reqparse, abort, Api, Resource
3
4app = Flask(__name__)
5api = Api(app)
6
7TODOS = {
8 'todo1': {'task': 'build an API'},
9 'todo2': {'task': '?????'},
10 'todo3': {'task': 'profit!'},
11}
12
13
14def abort_if_todo_doesnt_exist(todo_id):
15 if todo_id not in TODOS:
16 abort(404, message="Todo {} doesn't exist".format(todo_id))
17
18parser = reqparse.RequestParser()
19parser.add_argument('task')
20
21
22# Todo
23# shows a single todo item and lets you delete a todo item
24class Todo(Resource):
25 def get(self, todo_id):
26 abort_if_todo_doesnt_exist(todo_id)
27 return TODOS[todo_id]
28
29 def delete(self, todo_id):
30 abort_if_todo_doesnt_exist(todo_id)
31 del TODOS[todo_id]
32 return '', 204
33
34 def put(self, todo_id):
35 args = parser.parse_args()
36 task = {'task': args['task']}
37 TODOS[todo_id] = task
38 return task, 201
39
40
41# TodoList
42# shows a list of all todos, and lets you POST to add new tasks
43class TodoList(Resource):
44 def get(self):
45 return TODOS
46
47 def post(self):
48 args = parser.parse_args()
49 todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
50 todo_id = 'todo%i' % todo_id
51 TODOS[todo_id] = {'task': args['task']}
52 return TODOS[todo_id], 201
53
54##
55## Actually setup the Api resource routing here
56##
57api.add_resource(TodoList, '/todos')
58api.add_resource(Todo, '/todos/<todo_id>')
59
60
61if __name__ == '__main__':
62 app.run(debug=True)
63