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.

70 lines
2.2KB

  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. from .relationships import *
  14. import pandas as pd
  15. import json
  16. api = Blueprint('api', __name__)
  17. # function to get different types from the Resource database table
  18. def get_resource_json(resource_type):
  19. resources = Resource.query.filter_by(type=resource_type)
  20. if (resource_type=='tool'):
  21. resources_schema = ToolSchema(many=True)
  22. elif (resource_type=='practice'):
  23. resources_schema = PracticeSchema(many=True)
  24. elif (resource_type=='book'):
  25. resources_schema = BookSchema(many=True)
  26. result = resources_schema.dump(resources)
  27. # return all rows as a JSON array of objects
  28. result = jsonify(result)
  29. return result
  30. # route for api page
  31. @api.route('/api')
  32. def api_page():
  33. return render_template('api.html')
  34. # route for exporting all users in database
  35. @api.route('/api/users')
  36. @login_required
  37. def get_users_json():
  38. users = User.query.all()
  39. users_schema = UserSchema(many=True)
  40. result = users_schema.dump(users)
  41. # return all rows as a JSON array of objects
  42. return jsonify(result)
  43. # route for exporting all tools in database
  44. @api.route('/api/tools')
  45. def get_tools_json():
  46. resource_type = 'tool'
  47. output = get_resource_json(resource_type)
  48. return output
  49. # route for exporting all practices in database
  50. @api.route('/api/practices')
  51. def get_practices_json():
  52. resource_type = 'practice'
  53. output = get_resource_json(resource_type)
  54. return output
  55. # route for exporting all books in database
  56. @api.route('/api/books')
  57. def get_books_json():
  58. resource_type = 'book'
  59. output = get_resource_json(resource_type)
  60. return output