Search code examples
phprestapiswaggerswagger-2.0

PHP REST API with Swagger - LiveHelperChat


I downloaded Live Helper Chat (an Open Source application built with PHP) from here: https://livehelperchat.com/, and I have been trying to add a custom endpoint to the REST API which is built on Swagger 2.0.

So far, I

1) Added the path in swagger.json like this:

    "/restapi/myendpoint/{user_id}": {
  "get": {
    "tags": [
      "user"
    ],
    "summary": "",
    "description": "",
    "produces": [
      "application/json"
    ],
    "parameters": [
      {
        "name": "user_id",
        "in": "path",
        "description": "User ID",
        "required": true,
        "type": "string",
        "format": "int32"
      }
    ],
    "responses": {
      "200": {
        "description": "",
        "schema": {
        }
      },
      "400": {
        "description": "Error",
        "schema": {
        }
      }
    },
    "security": [
      {
        "login": []
      }
    ]
  }
}

2) created a file named myendpoint.php under modules/lhrestapi :

<?php

try {
erLhcoreClassRestAPIHandler::validateRequest();

$user = erLhcoreClassModelUser::fetch((int) $Params['user_parameters'] 
['user_id']);

if ($user instanceof erLhcoreClassModelUser) {

    $db = ezcDbInstance::get();

    echo json_encode(array('error' => false, 'result' => array('msg' => 
'Status changed', 'online' => $user->hide_online == 0)));

} else {
    throw new Exception('User could not be found!');
}

} catch (Exception $e) {
echo erLhcoreClassRestAPIHandler::outputResponse(array(
    'error' => true,
    'result' => $e->getMessage()
));
}

exit();

and

3) added this inside lhrestapi\module.php :

$ViewList['myendpoint'] = array(
'params' => array('user_id')
);

When I try this endpoint, I am getting code 302 (a redirect to /index.php/) as if the route doesn't exist.

As far as I can see from the other endpoints in the API, these changes should be enough to get a new endpoint.

Note: I also tried changing the path of one of the existing paths inside swagger.json, and the endpoint still works with the old path. I am starting to think there is some command that I need to run to update the API since simply editing the swagger.json file seems to have absolutely no effect whatsoever. On the other hand, I am positive there are no syntax errors in the code I added.

Any idea what I am not doing correctly?


Solution

  • Found the answer: when changes are made, the cache needs to be cleared or even disabled while developing. More details here: https://livehelperchat.com/article/view/40