Clients communicating with backend Server running Drupal 8 web app
Clients communicating with backend Server running Drupal 8/9

Drupal — RESTful API’s validation the simple way

Vishwa Chikate
4 min readDec 19, 2021

The RESTful Web Services API is newly introduced in Drupal 8, with Drupal 7 we used the Services module for creating RESTful Web API’s but things have changed in Drupal 8 as it provides most of the REST related features in its Core.

In this article we cover alternative approaches which can be introduced to handle API validation in Drupal 8/9 or any PHP based project, thereby further reducing the need to write needless custom code to validate the HTTP request. I hope the following implementation practice which we use at Srijan Technologies can help:

#1 : Entities and its corresponding RESTful API’s:

Entity

Assume we have a Vehicle ” Entity created in Drupal having the following fields :

  • Name (Text, required)
  • Company (Text, required)
  • Manufacture year (Number, required)
  • Mileage (Number, required)
  • Transmission type (Text, required)
  • Owner (Text, optional)
  • Registration number (Number, optional)
Structure of the “Vehicle” Entity is as follows Fields name, company, manufacture_year and transmission_type are required while creating a new entry i.e they must have a user submitted value. Whereas fields owner and registration_year are optional and will have default values.
Vehicle Entity with their constraint

Structure of the “Vehicle” Entity is as follows Fields name, company, manufacture_year and transmission_type are required when creating a new entry i.e they must have a user submitted value. Whereas fields owner and registration_year are optional and will have default values if passed empty.

RESTful API’s

We design the following REST endpoints to handle all CRUD operations on the Entity “ Vehicle ”.

  • /vehicles : GET : Retrieve a list of all vehicles
  • /vehicles/{id}: GET : Retrieve vehicle of the given Id
  • /vehicles : POST : Create a new vehicle
  • /vehicles/{id} : PUT/PATCH: Edit existing vehicle
  • /vehicles/{id} : DELETE : Delete vehicle with given Id

#2 : Validating POST/PUT/PATCH HTTP requests

We will consider JSON as the data interchange format in all of the code snippets below. All the code snippets are written considering Drupal 8/9 as the backend.

The JSON data :

{
"name": "Punch",
"company": "TATA",
"manufacture_year": 2021,
"mileage": 20.0,
"transmission_type": "manual",
"owner": "",
"registration_number": ""
}

Example 1 (The BAD way):

Below code snippet shows the POST request handler for the REST API /vehicles, this is how most of us would have introduced validation in the code.

Although the above code works perfectly fine, but unknowingly we have added unnecessary noise to the code in the form of additional conditional checks.

Disadvantages :

  • The function “post()” in a way is also a type of Controller method, we have purposely written a FAT controller which is considered a bad programming paradigm.
  • Affects readability/maintainability of the code.
  • If a new required field is introduced in the Entity/POST data, we might need to add newer validations.
  • The need to throw and handle Exceptions.
  • Approach too Naive, when working with huge Entities/Models.

Example 2 (Fair way):

Below we create a new Class called VehicleValidator to handle validation of the data posted from Client. This approach is better than the first Example, as there is a separate class to handle the data validation. Code looks clean as the readability/maintainability has improved.

This type of code can be useful in many scenarios but still the need to write a custom validation Class has been introduced.

Disadvantages :

  • Need to write Custom validators.
  • We might end up writing Validators for each Entity/Model. Even thinking of a Common validator Class is good idea, still the question remain’s on how many different methods to add to that class.
  • The need to throw and handle Exceptions.

Example 3 (The Good/Clean/Simple way):

We will use third party library to validate POST/PUT/PATCH/GET HTTP requests. Add the following third party PHP library justinrainbow/json-schema in project using composer.

composer require justinrainbow/json-schema

Create a Schema/Model file which matches exactly to the json content . Considering the Vehicle schema defined above we create the following php file and include it to the current code base/module. More detailed explanation on the usage of library’s can be found on its Official : page justinrainbow/json-schema.

In-short we have defined the type of json schema expected at the endpoint “/vehicles” when method is POST and also defined what fields must be present in the JSON and their corresponding data types.

Integrating with the actual code :

Advantages of this approach — They are almost the opposite of disadvantages mentioned above 😃

I cannot think of any major dis-advantages with the above approach. If you find any do point it out to me in the below comments sections.

Screenshots of Validation error thrown by the library :

Examples of Error thrown by the justinrainbow/json-schema PHP library

Conclusion

Went through alternative approaches which can be used to validate REST API request. Developers can use any library of their choice.

I do not claim this approach is the BEST, there can be many better than this but the whole idea which me and my team believed was to have a clean/re-usable approach in validating most of the HTTP requests.

Thanks, Happy Reading

--

--