API routing

api.v1

Neoan3 ships with a REST structured JSON API (v1). Its base url is /api.v1. When running the development server, your endpoints therefore start with http://localhost:8080/api.v1, followed by your component name.

1. Create an API endpoint
neoan3 new component myEndpoint -t:api

Note!

Regardless of component type, endpoints resolve kebab case. The full url of this example would therefore be
http://localhost:8080/api.v1/my-endpoint

2. Define available methods
Within the generated component controller, you can define available methods by prepending the method. In order to create a GET-endpoint, you would therefore create the method getMyEndpoint().

3. Handle parameters/body
By defining parameters, you dictate how the API will interpret the validity of calls made against the endpoint. It allows you to handle various possible combinations and define whether or not parameters are optional.

Examples

Definition Fails Works
getMyEndpoint() GET api.v1/my-endpoint
GET api.v1/my-endpoint/ABC123
getMyEndpoint(string $id) GET api.v1/my-endpoint GET api.v1/my-endpoint/ABC123
getMyEndpoint(?string $id=null) GET api.v1/my-endpoint
GET api.v1/my-endpoint/ABC123
getMyEndpoint(?string $id=null, array $params) GET api.v1/my-endpoint GET api.v1/my-endpoint?some=value
GET api.v1/my-endpoint/ABC123?some=value

4. Handle Errors
The API will automatically throw request errors for malformed requests of any sort. However, in some cases you will want to return such errors yourself. To do so, feel free to use Neoan3\Core\RouteException.
e.g. throw new RouteException('unauthorized', 401);
The API will respond with the right headers and status.

5. Handle results
Your method simply needs to return any value that can be encoded into a JSON response. In most cases, returning an array is the right choice.
return ['request'=>'accepted'];

Neoan3 ships with a similar example. Please feel free to have a look at /component/Endpoint