In this blog post, I describe how I wrote API schema and endpoints for an already existing database model in the Open Event API Server. Following this blog post, you can learn how to write similar classes for your database models. Let’s dive into how the API Schema is defined for any Resource in the Open Event API Server. Resource, here, is an object based on a database model. It provides a link between the data layer and your logical data abstraction. This ResourceManager has three classes.
- Resource List
- Resource Detail
- Resource Relationship
(We’ll take a look at the Speakers API.)
First, we see the already implemented Speaker Model :
Here’s the Speaker API Schema:
Last piece of code is listing the actual endpoints in __init__ file for flask-rest-jsonapi
How to write API schema from database model?
Each column of the database model is a field in the API schema. These are marshmallow fields and can be of several data types – String, Integer, Float, DateTime, Url.
Three class definitions follow the Schema class.
SpeakerList class is the basis of endpoints:
api.route(SpeakerList, 'speaker_list', '/events/<int:event_id>/speakers', '/sessions/<int:session_id>/speakers', '/users/<int:user_id>/speakers')
This class will contain methods that generate a list of speakers based on the id that is passed in view_kwargs. Let’s say that ‘/sessions/<int:session_id>/speakers’ is requested. As the view_kwargs here contains sesssion_id, the query methods in SpeakerList class will fetch a list of speaker profiles related to the sessions identified by session_id.
The flask-rest-jsonapi allows GET and POST methods for ResourceList. When using these endpoints for POST, the before_create_object and before_post methods can be written. These methods are overridden from the base ResourceList class in flask-rest-jsonapi/resource.py when they are defined in Speaker’s class.
SpeakerDetail class provides these endpoints:
api.route(SpeakerDetail, 'speaker_detail', '/speakers/<int:id>')
The Resource Detail provides methods to facilitate GET, PATCH and DELETE requests provided for the endpoints. Methods like: before_get_object, before_update_object, after_update_object are derived from ResourceDetail class. The endpoints return an object of the resource based on the view_kwargs in a JSON response.
SpeakerRelationship class, as you might have guesses, provides:
api.route(SpeakerRelationship, 'speaker_event', '/speakers/<int:id>/relationships/event') api.route(SpeakerRelationship, 'speaker_user', '/speakers/<int:id>/relationships/user') api.route(SpeakerRelationship, 'speaker_session', '/speakers/<int:id>/relationships/sessions')
SpeakerRelationship class provides methods to create, update and delete relationships between the speaker and related resources – events, users and sessions in this case.
The above is a bare bone API schema example. The actual implementation in Open Event Server has lots of helper methods too to cater to our specific needs.