Skip to main content

JSight Validator PHP Manual

JSight PHP Validator is a PHP extension, which validates all your API requests and responses against your API specification, written with JSight API language.

JSight Validator is 100% free.

Installation guide

Step 1. Install JSight Shared Library

1.1. Download JSight Shared Library libjsight.so:

OSJSight Shared Library
Linux x64libjsight.so v.1.0.0
mv libjsight.so /usr/local/bin/
info

You can put libjsight.so in any other folder, but in this case, you should specify its path later in JSight PHP Extension configuration.

Step 2. Install JSight PHP Extension

2.1. Download JSight PHP Extension jsight.so:

PHP VersionOSJSight PHP Extension
8.2Linux x64jsight.so v.1.0.1 (PHP 8.2)
8.1Linux x64jsight.so v.1.0.1 (PHP 8.1)
8.0Linux x64jsight.so v.1.0.1 (PHP 8.0)

2.2. Move jsight.so to PHP extensions folder

mv jsight.so `php-config --extension-dir`/

2.3. Load the extension in PHP INI file

Add these lines to your php.ini configuration:

extension=jsight.so

;jsight.lib_dir=/usr/local/lib
;jsight.max_threads_count=1
info

Instead of modifying php.ini, you can create jsight.ini file in conf.d directory and copy the above-mentioned lines there.

Learn more about PHP runtime configuration on official PHP configuration manual.

2.4. Configure PHP extension (optional)

You may uncomment and specify jsight configuration options in php.ini, e. g.:

extension=jsight.so

jsight.lib_dir=/my-jsight-shared-library-folder
jsight.max_threads_count=1
  • jsight.lib_dir specifies the directory path, where libjsight.so shared library is located, by default it is /usr/local/bin;
  • jsight.max_threads_count specifies the maximum number of threads per process, which will be used for message validation. By default, it equals the number of CPU cores. Usually, you do not need to specify this option, since it may be required only for highload services. This option sets the GOMAXPROCS runtime variable.

2.5. Check that everything is fine

If JSight PHP Extension is properly installed, you will see it in the list printed by this command:

php -r "print_r(get_loaded_extensions());"

Also you can render phpinfo() on any of your HTML page:

<?php
phpinfo();
?>

On phpinfo() rendered page, you will be able to find jsight section, like this:

JSight in phpinfo()

 

SUPPORT

If you face any issues with installing and configuring the JSight Shared Library or JSight PHP Extension, please feel free to write to our support:

Quick Start Guide

Pure PHP

Using JSight with PHP is very simple. The basic API call validation use case is shown in the following example.

1. Create the API specification file my-api-spec.jst with this content in your PHP server root folder:

JSIGHT 0.3

POST /user.php // Create a user
Request
@user
200
"OK"

TYPE @user
{
"id": 1,
"login": "tom",
"name": "John" // {optional: true}
}

2. Create the file user.php with this code in the same folder:

<?php
jsight_clear_cache(); // Do not forget to comment this line on production.

// validate request
$error = jsight_validate_http_request("./my-api-spec.jst", $_SERVER["REQUEST_METHOD"], $_SERVER["REQUEST_URI"], getallheaders(), file_get_contents("php://input"));
if( $error ) {
http_response_code(400);
echo jsight_serialize_error("json", $error);
exit;
}

// process API call
$responseBody = "\"OK\"\n";

// validate response
$error = jsight_validate_http_response("./my-api-spec.jst", $_SERVER["REQUEST_METHOD"], $_SERVER["REQUEST_URI"], http_response_code(), headers_list(), $responseBody);
if( $error ) {
http_response_code(500);
echo jsight_serialize_error("json", $error);
exit;
}

// respond
echo $responseBody;

3. Test your API with a valid request:

curl -X POST -d '{"id": 1, "login": "hello"}' localhost/user.php

You will get a successful response, like this:

$ curl -X POST -d '{"id": 1, "login": "hello"}' localhost/user.php
"OK"

4. Test your API with an invalid request:

curl -X POST -d '{"id": 1}' localhost/user.php

You will get a validation error, something like this:

$ curl -X POST -d '{"id": 1}' localhost/user.php
{
"reportedBy": "HTTP Request validation",
"type": "http_body_error",
"code": 32001,
"title": "HTTP body error",
"detail": "Required key(s) \"login\" not found",
"position": {
"index": 0,
"line": 1,
"col": 1
}
}

That's it! For more info on JSight Validator functions learn the Function Reference section.

Laravel

You can start using JSight on Laravel in 5 minutes. Just perform three simple steps:

  1. Describe your API using JSight API language.
  2. Setup JSight middleware.
  3. Test your API.

Step 1. Describe your API

  1. Create a folder for your API specifications in your Laravel root folder, e. g. ./jsight/.
  2. Create a file, which will contain your API specification, e. g. ./jsight/my-api.jst in this folder.
  3. Specify your API in ./jsight/my-api.jst file using JSight API language. You can use JSight Online Editor for this purpose.

For example, you can use this demo API specification:

my-api.jst
JSIGHT 0.3

GET /api/users // Returns all users.
200 [@user]

POST /api/users // Creates a new user
Request @user
200 @user

GET /api/users/{id} // Returns a user with the specified id.
200 @user

TYPE @user
{
"id": 1,
"login": "tom",
"name": "Tomas" // {optional: true}
}

Step 2. Set up JSight middleware

  1. Create JSight.php file in Laravel ./app/Http/Middleware folder for middlewares with the following content:
JSight.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class JSight
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if (!$request->is("api/*")) {
return $next($request); // skip not api calls
}

if (config("app.debug")) {
jsight_clear_cache();
Log::warning("JSight cache cleared (enable jsight cache by setting `APP_DEBUG=false` in `.env` file)");
}

$jsightSpecPath = base_path()."/jsight/my-api.jst"; // !!! PUT YOUR JSIGHT SPECIFICATION PATH HERE

$err = jsight_validate_http_request(
$jsightSpecPath,
$request->method(),
$request->getRequestUri(),
$request->headers->all(),
$request->getContent()
);

if ($err) {
$s = jsight_serialize_error("json", $err);
return response($s, 400)->header("Content-Type", "application/json");
}

$response = $next($request);

if ($response->status() === 500) {
return $response;
}

$err = jsight_validate_http_response(
$jsightSpecPath,
$request->method(),
$request->getRequestUri(),
$response->status(),
$response->headers->all(),
$response->getContent()
);

if ($err) {
$s = jsight_serialize_error("json", $err);
return response($s, 500)->header("Content-Type", "application/json");
}

return $response;
}
}
  1. Specify you real JSight API specification filename in JSight.php in this line:
    $jsightSpecPath = base_path().'/jsight/my-api.jst';.

  2. Register the JSight middleware in ./app/Http/Kernel.php.
    For this purpose, add \App\Http\Middleware\JSight::class to the $middleware variable of the HttpKernel class. Like this:

Laravel HttpKernel middleware

Step 3. Test your API with an invalid request:

curl -X POST -d '{"id": 1}' localhost/api/users

You will get a validation error, something like this:

$ curl -X POST -d '{"id": 1}' localhost/api/users
{
"reportedBy": "HTTP Request validation",
"type": "http_body_error",
"code": 32001,
"title": "HTTP body error",
"detail": "Required key(s) \"login\" not found",
"position": {
"index": 0,
"line": 1,
"col": 1
}
}

That's it! Your JSight middleware is installed. Now all your API requests and responses will be validated against the JSight API specification.

info

JSight.php middleware is very simple and straightforward. You can always adjust it according to your needs.

You can learn more about Laravel middleware in the official Laravel Middleware tutorial.

You can learn more about JSight Validator functions in the Function Reference section.

Function Reference

jsight_clear_cache

Clears JSight Validator cache (where compiled API Specifications are cached).

Description

jsight_clear_cache()

It is useful to call jsight_clear_cache() in debug mode each time before data validation.

info

Avoid calling jsight_clear_cache() in production mode! It slows down validation dramatically.

jsight_serialize_error

Serializes message validation error into a string in a specified format.

Description

jsight_serialize_error(string $format, array $error): string

Input parameters:

  • $format — serializing format. Only json format is supported in this version.
  • $error — an array, which contains validation error data. This array is returned in case of validation error by functions: jsight_validate_http_request(…), jsight_validate_http_response(…).

Returns serialized string, according to the specified $format.

Usage example:

$error = jsight_validate_http_request($jsightSpecPath, $method, $uri, getallheaders(), $requestBody);

if( $error ) $response = jsight_serialize_error('json', $error);

jsight_stat

Returns current JSight Shared Library status info (CPU usage, memory usage, thread usage, etc.).

Description

jsight_stat(): string

jsight_validate_http_request

Validates HTTP request against JSight API specification.

Description

jsight_validate_http_request(
string $api_spec_file_path,
string $request_method,
string $request_uri,
array $request_headers = null,
string $request_body = null
): array | null

Input parameters:

  • $api_spec_file_path — a path to a JSight API specification file.
  • $request_method — HTTP 1.1 method name in upper case (e. g. "GET").
  • $request_uri — a request URI string, starting from /.
  • $request_headers — an associative array of request headers, where array keys contain header names and array values contain header values of type string or array of header values of type string (see example below).
  • $request_body — an HTTP request body string.

Returns null if the HTTP request is valid. Returns validation error array if validation fails.

Usage example:

$headers = array(
'Content-Type' => 'application/json',
'Set-Cookies' => [ '123', '456' ]
);

$error = jsight_validate_http_request($jsightSpecPath, $method, $uri, $headers, $requestBody);

if( $error ) $response = jsight_serialize_error('json', $error);

jsight_validate_http_response

Validates HTTP response against JSight API specification.

Description

jsight_validate_http_response(
string $api_spec_file_path,
string $request_method,
string $request_uri,
string $response_status_code,
array $response_headers = null,
string $response_body = null
): array | null

Input parameters:

  • $api_spec_file_path — a path to a JSight API specification file.
  • $request_method — HTTP 1.1 method name in upper case (e. g. "GET").
  • $request_uri — a request URI string, starting from /.
  • $response_status_code — a string (or an integer), representing response HTTP status code.
  • $response_headers — an associative array of response headers, where array keys contain header names and array values contain header values of type string or array of header values of type string (see example below).
  • $response_body — an HTTP response body string.

Returns null if the HTTP response is valid. Returns validation error array if validation fails.

Usage example:

$headers = array(
'Cache-Control' => 'no-store',
'Set-Cookies' => [ '123', '456' ]
);

$error = jsight_validate_http_response($jsightSpecPath, $method, $uri, $statusCode, $headers, $responseBody);

if( $error ) $response = jsight_serialize_error('json', $error);