REST API and frontend redundancies, what is good practice?

Hey guys,

I’m running into a situation where our frontend controllers and REST API controllers have redundant code. Let me give you an example:

Users need to be logged in to view images. Our ImageController has an actionThumbnail() method that does:

  • checks that the user has access to the image (uses Yii2 controller access rules before entering the action method)

  • checks cache for thumbnail

  • generates if not in cache (this is code within a model)

  • sets return headers

  • returns image.

Now the REST API has a thumbnail feature that does exactly the above. We don’t want to copy/paste the code from the frontend into the API controller. But from reading around it isn’t good practice to simply call the frontend controller action (understandably).

I originally considered just implementing the API and having the application hit the API up for thumbnails and similar redundant features but because the API does not hold user sessions and uses a different Authentication system we seem to run into issues.

What would good practice be in this case. We have this same issue with many other features.

Thanks for your help.

In this case it could be a good idea to create a separate action and attach it to both controllers:

Awesome thanks!

I guess this combined to custom access rules would be the best way to remove any duplicates.