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?
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
Related
I'm working on a project and I came across a problem, explain:
I'm doing a POST to a webserver using the Guzzle http, follows the :
public function sendPost($direction, array $data, array
$options = ['http_errors'=>false])
{
$url = $this->interpolate( self::BASE_PATH."/{direction}",
[
'direction' => $direction
]);
$options = array_merge($options,['body'=>json_encode($data)]);
return $this->client->post($url, $options);
}
The method is working correctly and I am returning the following:
{
"id": "jdhj9h830027hd73hs9q9js9",
"direction": "left",
"status": "Success",
"code": {
"id":"1",
"desc": "ok",
"error": false,
"msg":null
}
}
What I can not do is the following:
A method that returns only the given "jdhj9h830027hd73hs9q9js9", that is, the "id" parameter.
can anybody help me?
PS. By using the "sendPost ()" method I can access the data I need separately, however I can not do this through another method, such as a "getId ()".
Thank you in advance for your help.
Just try:
return ($this->client->post($url, $options))->id;
https://github.com/hasbridge/php-json-schema
Getting error Class 'JsonValidator' not found.
I did install composer.json as in git folder.
I did put my json schema, json data files in src/Json and created a php file to validate as mentioned in git.
getting error class Class 'JsonValidator' not found.
In their example, they're creating a JsonValidator object.
This is different from the actual namespace of the class, which is Json\Validator.
Try dropping use Json\Validator as JsonValidator at the top of your file so that you're able to refer to the class the same way the docs do.
I'd expand their docs from:
$someJson = '{"foo":"bar"}';
$jsonObject = json_decode($someJson);
$validator = new JsonValidator('/path/to/yourschema.json');
$validator->validate($jsonObject);
To
<?php
namespace Your\Domain;
use Json\Validator as JsonValidator;
require_once('./vendor/autoload.php');
$someJson = '{"foo": "bar"}';
$jsonObject = json_decode($someJson);
$validator = new JsonValidator('/path/to/yourschema.json');
$validator->validate($jsonObject);
Alternatively, you could substitute new JsonValidator('/path/to/yourschema.json') for new Json\Validator('/path/to/yourschema.json').
Edit: By the way - you might find the example schemas at json-schema.org helpful when using this library.
Here's the main one from that link:
{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
Save this file somewhere in your project and refer to it instead of /path/to/yourschema.json.
I'm using spark in codeigniter as a rest client to talk to the service. The apis are already built separately in swagger.
I'm trying to do an user login functionality. This is my api model schema:
{
"name": "string",
"email": "string",
"password": "string",
"mobile": "string",
"accType": "string",
"meta": "string",
"createdAt": 0
}
For testing user existence, this is my code :
function __construct(){
parent::__construct();
$this->load->library('rest', array(
'server' => 'http://stage.cogxio.co:7070/',
'api_key' => 'local',
'api_name' => 'X-API-KEY',
));
}
function user_exist($data){
$response = $this->rest->get('user/email/'.$data, 'json');
if(property_exists($response, "STATUS")){
$result_code = $response->STATUS;
if($result_code == 200){
return true;
}else{
return false;
}
} else {
return "server error";
}
}
The return of 1 will tell that the email exists otherwise does not exist.
When that checking is over, then I need to check whether the email and password are matching, that is "WHERE email=$email && password=$password"
Since, I'm new to api, I don't know how to do that.
I know, I need to pass two variables.
function login_match($email, $password){
$response = $this->rest->get('user/email/??, 'json'); // what to do with this field?
}
I don't know how to use the where clause here.
I'm going around in circles trying to get this to work...
Here's the situation:
I have a PHP web app which makes remote procedure calls (RPCs) to several microservices via a Crossbar.io router using Thruway. Anonymous calls are working perfectly, but now I want to add authentication.
Here is the Crossbar configuration:
{
"controller": {
},
"workers": [
{
"type": "router",
"realms": [
{
"name": "dashboard",
"roles": [
{
"name": "microservice",
"permissions": [
{
"uri": "*",
"publish": true,
"subscribe": true,
"call": true,
"register": true
}
]
}
]
}
],
"transports": [
{
"type": "websocket",
"endpoint": {
"type": "tcp",
"port": 80
},
"auth": {
"wampcra": {
"type": "static",
"users": {
"client1": {
"secret": "secret1",
"role": "microservice"
}
}
}
}
}
]
}
]
}
The Crossbar server is (I hope) set up as a router only. All clients/workers are on other servers. I've been following this example for the Crossbar config - specifically, this configuration file. There are a couple of important differences between the example and my config: the example server is configured as both a router and also serves static web pages (which mine does not) and the example server includes a Python component which (if I'm reading it correctly) is not material to the authentication process.
In my development environment I'm trying to get authentication to work for one client. Here's the client code:
<?php
// include the autoloader
//
require __DIR__ . '/vendor/autoload.php';
use Thruway\ClientSession;
use Thruway\Peer\Client;
use Thruway\Transport\PawlTransportProvider;
use Thruway\Authentication\ClientWampCraAuthenticator;
// create the WAMP client
//
$client = new Client('dashboard');
$auth = new ClientWampCraAuthenticator("client1", "secret1");
$client->addClientAuthenticator($auth);
// add the WAMP transport provider
//
$client->addTransportProvider(
new PawlTransportProvider('ws://192.168.1.10/')
);
// handle the "open" (connect) event
//
$client->on('open', function (ClientSession $session) {
// register the getImageData procedure
//
$session->register('service.client1.get', function ($data) {
return (new Client)->get();
});
});
// start the client
//
$client->start();
The problem is that the "challenge" message is never sent by the server. When the client attempts to connect, I get the following debug message:
2015-07-07T13:58:17.7451860 debug [Thruway\Transport\PawlTransportProvider 204] Received: [3,{"message":"no user with authid 'anonymous' in user database"},"wamp.error.not_authorized"]
Can anyone explain what additional configuration I need to do to get the server to challenge the client?
I found it...
I must have overlooked this in all the examples I've seen today. The solution is to add $client->setAuthId('client1'); before the call to $client->addClientAuthenticator($auth);
Restler is refusing to instantiate any of my API classes. It's just always saying it fails on Route, but doesn't bother to provide any other useful information. I installed Restler via composer via "restler/framework" : "3.0.0-RC6" and then created an index.php that looks like this:
<?php
require __DIR__.'/../vendor/autoload.php';
use Luracast\Restler\Restler;
$r = new Restler();
$r->addAPIClass('Explorer');
$r->addAPIClass('Play');
$r->handle();
In the exact same directory as the index.php I've created a file called Play.php that looks like so:
<?php
public class Play
{
public function __construct() {
error_log("I called the constructor!\n", 3, '/tmp/scott');
}
public function index() {
error_log("I called the index\n", 3, '/tmp/scott');
}
When I call http://.../api/play I never see the /tmp/scott file created, and I just get the generic failure response from Restler:
{
"error": {
"code": 404,
"message": "Not Found"
},
"debug": {
"source": "Routes.php:438 at route stage",
"stages": {
"success": [
"get"
],
"failure": [
"route",
"negotiate",
"message"
]
}
}
}
As Luracast noted in the comments, I had to edit the composer.json to add this stanza:
"autoload": {
"psr-0": {
"": "api"
}
}
and then run composer dump-autoload