0

Let's say I have two models in SqlAlchemy:

  • UserType
  • User

User has a foreign key to UserType

I have properly configured flask-restless to serve these models as API endpoints:

  • /api/user
  • /api/user_type

But by default, when I visit either of these endpoints, I get the related data associated with each object in the response:

  • Each User has the corresponding UserType object nested in the response
  • Each UserType has a collection of User nested in the response

This will definitely lead to a lot of overhead as the data grows a lot. If I just want to GET the list of UserType that the system supports, all of the associated users will come back. Usually an API would generate a link for related resources:

  • /api/user/1/user_type
  • /api/user_type/1/users

Has anyone gotten these links out of flask-restless responses?

kbuilds
  • 991
  • 11
  • 19

2 Answers2

0

It looks like this is a known issue that has been active on GitHub for a long time. Not sure if the developer is planning on fixing it or not:

https://github.com/jfinkels/flask-restless/issues/168#issuecomment-69821642

I ended up going with flask-restful and building my own endpoints.

kbuilds
  • 991
  • 11
  • 19
0

This is now implemented as of release 0.17.0

If your User model looks as follows:

class User(Base):
    id = Column(Integer, primary_key=True)
    username = Column(String)
    user_type_id = Column(Integer, ForeignKey("user_type.id"))
    user_type = relationship(UserType, backref=backref('users'))

and your UserType model looks like:

class UserType(Base):
    id = Column(Integer, primary_key=True)
    type = Column(String)
    description = Column(String)

Then you can fetch all users of a specific user_type by issuing a GET request to...

/api/user_type/1/users

...where the suffix /users/ is designated by the backref=backref('users') attribute passed to relationship() for the user_type column in User, and 1 is the id of the user_type being queried.

The Aelfinn
  • 13,649
  • 2
  • 54
  • 45