3. Request Handlers - nathan-fiscaletti/synful GitHub Wiki
Request handlers are a tool that Synful uses to parse data received from the user and send a response back.
RequestHandler Class
Each request handler implements the RequestHandler
class. The corresponding Request Type function on a RequestHandler will be automatically called by Synful when the corresponding EndPoint is requested by the user. (See Sending Requests).
There are several properties that you can override on the Request Handler. Some of these correspond to specific Middleware that you can implement and will have no effect if that Middleware is not implemented.
Property | Type | Effect | Required | Middleware |
---|---|---|---|---|
$endpoint |
string | Controls the URL end point for accessing the RequestHandler | true | None |
$middleware |
array(String) | The middleware to be applied to the RequestHandler. (See Middleware) | false | None |
$rate_limit |
array() | The rate limit to apply to the RequestHandler. (See Rate Limiting) | false | None |
$security_level |
int | If this value is set and it is greater than 0, only API keys with this security level or higher can access this RequestHandler. (See API Key Management) | false | APIKeyValidation |
$serializer |
String | The serializer to use for this RequestHandler. (This will override the setting in System.json) (See Serialization) | false | None |
Example Request Handlers
Synful comes packaged with several example Request Handlers. It's recommended that you go over these to better learn how Request Handlers operate.
Example Request Handler | Demonstrates |
---|---|
AdvancedEndpointsExample.php | Custom endpoint fields and their use |
GetInputExample.php | Retrieving input data from a GET request. (See Serialization: Applying a custom Serializer) |
GetIpExample.php | Public RequestHandlers |
HeaderExample | Using headers |
HttpCodeExample.php | Changing the HTTP response code |
InputExample | Getting input from the request |
MiddlewareExample | Using middleware |
PrivateHandlerExample.php | Private RequestHandlers (API Key endpoint access array) (see API Key management: Endpoint Access Array) |
RequestTypeExample.php | Different Request Types (POST, DELETE, GET, PUT) |
SecurityLevelExample.php | Securing RequestHandlers by overriding $security_level |
SerializerExample.php | Using a custom serializer implementation. |
Creating a RequestHandler
To create your request handler open a CLI interface and change directory to your Synful directory.
Synful has a few handy built in command line parameters that you can use. You can read more about those on the CLI Usage Run Through Wiki page.
Once you're in that directory, run one of the following commands.
$ ./synful -create-handler YourHandlerName
... or ...
$ ./synful -ch YourHandlerName
Where YourHandlerName
is the name of your new request handler.
Note: All request handler names are case sensitive. It is recommended that you use
TitleCase
when naming them.
Once run, there should be a new file created in src/Synful/App/RequestHandlers/
.
You will need to register the new RequestHandler class in ./config/RequestHandlers.json
to use it.
"registered": [
"Synful\\App\\RequestHandlers\\YourHandlerName"
]
Hint: Use the
-register
command.$ ./synful -register requesthandler YourHandlerName
Note: By default, the
$endpoint
property of the RequestHandler will be set to the request handlers name, as a lowercase string. See Endpoints
Writing your own Request Handler
After you've created your own Request Handler you can open it in editor to begin modifying it.
Each Request Handler can be set as one of three types. A Public Request Handler, a Private Request Handler, or a Secure Request Handler. By default they are all set to Public.
Hint: You can also use a combination of these to get different effects.
Request Handler Types
-
public
- When a Request Handler is set to public, it means that anyone can access that Request Handler without an API Key. This is generally not something you should do, unless you are specifically aiming for a public API. All request handlers are public by default. -
private
- When a Request Handler is set to private, it means that only keys with this Request Handlers endpoint associated in their Endpoint Access Array (see API Key management: Endpoint Access Array). To set a Request Handler to private, simply implement the APIKeyValidation Middleware and add the endpoint for the Request Handler to the API key using the-end-point-manage
command. -
secure
- When a Request Handler is set to secure, it means that it has a security level greater than 0 defined. Only API keys with a security level equal to or greater than that of this RequestHandler can access it. (This builds on top of aprivate
request handler, so the endpoint must also be in the API keys Endpoint Access Array). To set a RequestHandler to secure, simply implement the APIKeyValidation Middleware and override the$security_level
property. Set the$security_level
property to an integer greater than 0.
Read more on Middleware here.
Endpoints
By default, your request handler will use it's own name as a lowercase string for an endpoint. However you can configure this by overriding the $endpoint
property with your own custom endpoint.
public $endpoint = 'my/endpoint';
You can also add fields to the endpoint that can be extracted from the request.
public $endpoint = 'my/endpoint/{name}';
...
// Say you send a request to `http://127.0.0.1/my/endpoint/nathan`
$request->field('name'); // This would be equal to 'nathan'
Note: If you use a endpoint like
{type}/{id}
, i.e. there is no prefix for the endpoint, it will override all other endpoints on the system.
Serializers
You can override the global serializer on a per Request Handler basis to modify the way in which requests are received and responses are sent.
public $serializer = \Synful\Util\Serializers\JSONSerializer::class;
See Serialization
Request Type Functions
Asside from the property overrides that were mentioned under RequestHandler Class, there are several function overrides that can be used to override specific HTTP request types.
public function post(Request $request) ...
public function get(Request $request) ...
public function put(Request $request) ...
public function delete(Request $request) ...
public function patch(Request $request) ...
public function options(Request $request) ...
These functions by default will each throw a SynfulException if the RequestHandler is called and does not implement the specified Request Type.
These functions are used to handle requests sent to the RequestHandler. They each have only one parameter, $request
.
$request
- This is a reference to the Request object that was received from the client.
Request
You can access any data sent from the client via the $request
Request object.
To access keys sent by the user, use the ->input
function from the Request. This function takes a mapped key for the input. For example, say this request was sent to a Public
RequestHandler on your API:
{
"document": {
"people":[
{
"name":"Nathan"
}
]
}
}
We could then access this data with one of the following lines of code
$person_1_name = $request->input('document.people.0.name');
Read more on sending requests here.
Responding
There are two ways you can respond to the user.
- Returning an array
public function get(Request $request)
{
return [
'ip' => $request->ip,
];
}
Note: When returning an array, HTTP response code 200 is assumed.
- Returning a Response object
public function get(Request $request)
{
return sf_response(
200,
[
'ip' => $request->ip
]
);
}
You can also override the Serializer of a response itself. This way, you could force the RequestHandler to accept JSON request input, but output a CSV response.
See Serialization: Overriding Response Serializer for an example of this.
Click here for a list of HTTP response codes.
You can familiarize yourself further with the Response object by viewing the src/Synful/Util/Framework/Response.php
class.
Next: Sending Requests