PHP — RESTful API resource handler

Vishwa Chikate
2 min readJan 2, 2022

--

Photo by Luca Bravo on Unsplash

Here we will cover how can we better implement the callback Class/Methods a.k.a the resource handlers associated with an REST HTTP API. The idea which will be covered will help #developers in having a Reusable, Extendable and an easily Maintainable code.

The approach outlined here can be applied to any PHP framework of choice or it can be considered as implementation practice in other languages / framework’s. My Suggestion to the reader’s is to catch the main motive behind this article 😃

#1 : Entity and its RESTful API’s

Assume we have an Entity/Model Vehicle created with the following REST endpoint which returns a list of vehicles.

GET /vehicles : Retrieve a list of all vehicles

#2 : Resource Handler

While implementing the resource handler/function’s there are a lot of things which needs to be taken care by the #developer, some of the common tasks are listed below :

  • Authenticate the request
  • Validate the request
  • Get the HTTP query filters
  • Fetch the response / Write to database
  • Call other API’s (internal/external)
  • Build the response
  • Send the response

In short the resource handler can be composed of various layers, each of which has or performs some predominant task.

I have came across many #developers or Examples on the net which suggest to implement all the above layers in a single function which impacts the Readability, Extendability and Maintainability of the code.

Below diagram outlines the ideal way in which we should think of implementing the resource handlers. The code must be broken into layers and the main resource handler/function must only be concerned with understanding the request, validating it and sending back the response.

Rest resource handler layered implementation
Rest resource handler layered implementation

Code Snippet

Below is a pseudo code example Class written in PHP. The function ‘get() responds to all Client request made at the ‘URI GET : /vehicles’, it also performs all the tasks needed to fulfil the request made by the client and send’s back the associated response.

Each task is defined in its respective namespace of the project/module. Note the resource handler ‘get()’ is a type of a ‘Controller’ implemented by keeping in mind the Single Responsibility principle from the PHP’s Solid Principles set.

Conclusion

Alternate way which we follow while implementing most of the REST resource API’s in our project at Srijan Technologies. I do not claim that this is the best approach, if there are any better or there needs any correction to the above approach do let know in the comments below.

Thanks, Happy Reading

--

--