Optional Additional Parameters
When you are creating your API settings file, there are a range of optional parameters that you can declare for each of your endpoints. The optional parameters are as follows:
Required Fields
- required_fields: This will be an array of key value pairs, with each pair representing the name and the label for a required field. The code below declares an endpoint that has 'id' as a required field:
"Exists": {
"url_segments": "api/exists/members/{id}",
"request_type": "GET",
"description": "Check if instance exists",
"required_fields": [
{
"name": "id",
"label": "ID"
}
]
}
If you have a close look at the url_segments, above, you'll notice that the final segment is for 'id' and it's inside curly brackets. When you see this type of pattern in the URL segments, it means that we are expecting a value (in this case, 'id') to be passed in via the URL.
Before Hook
- beforeHook: The beforeHook parameter can be used to declare a method that should intercept the inbound HTTP request before allowing the request to reach the main endpoint method. Below is an example of an endpoint that has a beforeHook property of '_prep_password'. This endpoint will intercept the inbound HTTP request and run it through a method, on the loaded module, named _prep_password().
"Update": {
"url_segments": "api/update/trongate_administrators/{id}",
"request_type": "PUT",
"description": "Update a database record",
"enableParams": true,
"required_fields": [
{
"name": "id",
"label": "ID"
}
],
"authorization":{
"roles": [
"admin"
]
},
"beforeHook": "_prep_password"
}
The underscore at the start of _prep_password() means that the method is 'protected'. In other words, it cannot be invoked by going to a particular URL.
After Hook
- afterHook: The afterHook parameter can be used to declare a method that should receive the outbound server response before the response has been served to the end user. Below is an example of an endpoint that has an afterHook property of '_prep_date'. This endpoint will intercept the outbound HTTP response and run it through a method, on the loaded module, named _prep_date(). Our visualisation here would be a scenario where a date/time fetched from a database, such as a Unix timestamp, is to be formatted before being presented to the end user.
"Fetch Info": {
"url_segments": "fetch/{id}",
"request_type": "GET",
"description": "Fetch a database record",
"enableParams": true,
"required_fields": [
{
"name": "id",
"label": "ID"
}
],
"authorization":{
"roles": [
"admin"
]
},
"afterHook": "_prep_date"
}
Again, you can see that the after hook's method name begins with an underscore. This means that the method is protected.
Before hooks and after hooks are important. Let's explore them in a little more detail!