You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.0KB

  1. # @name: api.py
  2. # @creation_date: 2023-01-12
  3. # @license: The MIT License <https://opensource.org/licenses/MIT>
  4. # @author: Simon Bowie <ad7588@coventry.ac.uk>
  5. # @purpose: Exposes database data as exportable JSON for a RESTful API
  6. # @acknowledgements:
  7. # https://auth0.com/blog/developing-restful-apis-with-python-and-flask/
  8. # https://stackoverflow.com/questions/59721478/serializing-sqlalchemy-with-marshmallow
  9. from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify
  10. from flask_login import login_required, current_user
  11. from .models import Resource, User
  12. from .schemas import UserSchema, ToolSchema, PracticeSchema, BookSchema
  13. api = Blueprint('api', __name__)
  14. # route for api page
  15. @api.route('/api')
  16. def api_page():
  17. return render_template('api.html')
  18. # route for exporting all users in database
  19. @api.route('/api/users')
  20. @login_required
  21. def get_users():
  22. users = User.query.all()
  23. users_schema = UserSchema(many=True)
  24. result = users_schema.dump(users)
  25. # return all rows as a JSON array of objects
  26. return jsonify(result)
  27. def get_resource_json(type):
  28. resources = Resource.query.filter_by(type=type)
  29. if (type=='tool'):
  30. resources_schema = ToolSchema(many=True)
  31. elif (type=='practice'):
  32. resources_schema = PracticeSchema(many=True)
  33. elif (type=='book'):
  34. resources_schema = BookSchema(many=True)
  35. result = resources_schema.dump(resources)
  36. # return all rows as a JSON array of objects
  37. result = jsonify(result)
  38. return result
  39. # route for exporting all tools in database
  40. @api.route('/api/tools')
  41. def get_tools():
  42. type = 'tool'
  43. output = get_resource_json(type)
  44. return output
  45. # route for exporting all practices in database
  46. @api.route('/api/practices')
  47. def get_practices():
  48. type = 'practice'
  49. output = get_resource_json(type)
  50. return output
  51. # route for exporting all books in database
  52. @api.route('/api/books')
  53. def get_books():
  54. type = 'book'
  55. output = get_resource_json(type)
  56. return output