REST Overview Guide

Warning:

The steps provided in this explanation are based on Linx before release 6.4.0.

In Linx 6.4.0 and higher there is a Return function in the Linx plugin that must be used for setting the value of a function's result. The SetValue function and $.Result cannot be used for this purpose anymore.

Go here for details of the Return function.


The following sections cover a general overview of hosting and implementing REST web services in Linx with the use of the RESTHost function.

  • The flow of a REST request
  • The data structure of REST request in Linx
  • Supported HTTP status codes
  • Supported Media Types

REST Request Flow

When a request is made to a RESTHost service operation, the following flow takes place:

request flow

  1. Input deserialization and validation: After a request is received, Linx performs deserialization and validation of the inputs (query string, request body).
  2. Built-in security validations: Linx then executes built in .NET security validations according to the operation's applied HTTP security scheme (Basic, Bearer or API Key).
  3. Authentication event: Authentication event which is executed for Basic and API Key authentication. This allows you to add custom authentication logic for these schemes.
  4. Before operation event: Optional event which allows you to add custom logic to requests, before the operation is executed.
  5. Execute operation: Executes the operation in which the custom logic for the endpoint is built.
  6. After operation event: Optional event which allows you to add custom logic to requests, after the operation has been executed, regardless of success.
  7. Output serialization: Serialization of the outputs returned from the operation.
  8. Error handler: The whole flow is encapsulated in a built-in error handler.

Input deserialization and validation

After a request is received, the incoming requests parameters such as the request body or query values are deserialized and then validated according to the API definition.

If a validation error occurs, a (400) Bad Request response is returned along with a response body which contains the details of the invalid parameters.

Built-in security validations

Linx then executes built in .NET security validations according to the operation's applied HTTP security scheme.

Currently, the RESTHost service supports the following built-in security schemes:

  • HTTP Basic

  • HTTP Bearer

  • API Key

When a request is made to an operation that has one of the above security schemes applied to it, the following will happen:

  • Validation of authentication parameters:
    • Basic and API Key: Validate format (in header, in query etc).
    • Bearer: Automatically verify JWT token.

  • If unsuccessful, a (401) Unauthorized response is returned.
  • If successful, details associated with the authenticated user are passed through to the operation via:

    • For HTTP Basic and API Key security schemes, details are passed through to the operation in the AuthenticationData.
    • For the HTTP Bearer security scheme, details are passed through the to the operation in the HTTPContext.User

Authentication event

OperationEvents_Authenticate

Authentication event which is executed for HTTP Basic and API Key authentication schemes.

Whilst the security schemes are applied to the operation, there is no way to generically verify these credentials. Therefore, one must add custom authentication logic in this event to handle the verification of Basic and API Key authentication credentials. An example 2 of such logic would be confirming the validity of a API Key from a database.

By default, this event is set to return $.Result.Data.HttpContext.User.IsAuthenticated = False and therefore you must add logic in this event to indicate the authentication was successful. If the authentication fails, a (401) Unauthorized response is returned.

Before operation event

OperationEvents_BeforeOperation

You are able to add custom logic to this event which will execute before the operation is executed. This is applied to all the operations and custom logic could be things such as custom logging, throttling or additional custom authentication.

Execute Operation

The operation that contains your custom logic is executed once all the necessary validations have occurred.

By default, all operations are set to have a default response of (200) OK.

If want to return a different HTTP Status code like 201 or 402 then you can by setting a custom response.

After operation event

OperationEvents_AfterOperation

You are able to add custom logic to this event which will 'fire' after any operation has executed, regardless of the result.

Output serialization

The outgoing response properties are deserialized according to the API specification.

Error Handler

The whole flow is encapsulated in a built-in error handler, should an error occur at any of the stages in the flow then a (500) Internal Server Error will be returned. You have the option of including or omitting error details from the response by altering the Return server errors of the RESTHost service to True.

Structure of Linx REST Request

When a request is received or a response is returned, it is structured as follows:

Data

Highest-level request/response object.

Data Type Included in
HTTPContext httpContext Requests/Responses
AuthenticationData authenticationData Requests with security events
Input Parameters inputParameter Requests
ResponseXXX responseXXX Responses

HTTPContext

Object containing all metadata and additional information associated with the request.

HTTPContext Type Example
Connection connection
ContentLength Integer 12322
ContentType String Application/json
Cookies List x-api-key=aadedwde
Headers List
Host String localhost
IsHttps Boolean true
Items List ['User1','User2']
Method String GET
Path String /users
PathBase String /LinxSampleAPI/restHOST
Protocol String HTTP/2
Query List
QueryString String ?x-api-key= xsdshsdj37sh
Scheme String https
User user


Connection

Connection details associated with the source of the request.

Connection Type Example
ID String -485183435770848
LocalIpAddress String ::1
LocalPort Integer 443
RemoteIpAddress String ::1
RemotePort String 55023

Headers are used to pass additional information with the request. Typical usage involves the Authorization header used for authentication schemes such as Basic, Bearer or API Key.

Header Type Example
Key String Authorization
Value List < String > Bearer Xhsjjs73890s0


Query

Query values are used to pass additional information usually related to the request such as a filter value.

These are passed in with the HTTPContext.QueryString of the request URL, they are then deserialized into the following format:

Query Type Example
Key String x-api-key
Value List < String > ['xsdshsdj37sh']


User

Contains information related to the authenticated user from the built in security validations as well as from the OperationEvents_Authenticate event.

You are able to alter this property in order to pass data through to the subsequent events and operations.

An example of this could be if you validate an API key with custom logic in the OperationEvents_Authenticate event by matching the key to a user, you can then return the user’s id from the database which can be passed on to the main operation. This avoids re-extracting the identifiers that might be of use in the operation.

For the HTTP Bearer authentication scheme, the unique_name claim value is extracted from the JWT token and passed in with the User.Name property.

User Type Example
AuthenticationType String 2
IsAuthenticated Boolean true
Name String 2233


Input Parameters

When parameters are passed in with a request in either the request URL, query string or request body, they are deserialized and accessible in the $.Input.Data property of the operation and events:

Input Parameter Type Example
URL parameters String /users/45
Query values String Name=John
Header values String Name=John
Cookies String Name=John
Request Body Text/XML/JSON/Filestream/URL Encoded "user" { "name" : "John"}


ResponseXXX

By default, when an operation completes, a (200) OK response status code with a response body of no-content is returned. However, you are also able to return custom response codes as well as custom response content which can be basic types or objects containing nested types and objects.

Output Type
Response Body JSON/XML/Binary


AuthenticationData

When the built-in security validations have succeeded, details relating to the authenticated user will be passed on to any operations and events down the request flow.

AuthenticationData Type Example
SchemeName String BasicAuth
SchemeType schemetype 1
ApiKey String ApiKey


For HTTP Basic only the SchemaName and SchemeType will be returned, you will need to parse the headers for the credentials and decode them using custom logic.

For API Key, all the details are returned including the actual API Key.

For HTTP Bearer , the AuthenticationData is not present, rather details are passed through the User object.

APIKey

The API Key object will contain the below information if the security scheme for the operation is API Key. If the authentication is HTTP Basic, then this object will be NULL.

ApiKey Type Example
TokenLocation tokenLocation 2
TokenName String X-API-KEY
ProvidedToken String 0imfnc8mVLWwsAawjYr4Rx-Af50DDqtlx


HTTP Status Code Support

General Status Code Support

The following HTTP Status Codes are supported in the RESTHost operation responses.

Built-in

Status Code Phrase Use
200 OK Default response code for all operations unless set otherwise.
401 Unauthorized Default response code for security validation failures or authentication failures.
400 Bad Request Default response for incorrect structure of request.
415 Unsupported Media Type Default response for unsupported media in the content-type header.
500 Internal Server Error Default response code when an unhandled exception occurs in the request flow. Users are able to include or omit the server errors from the response.


Custom

Status Code Phrase Use
1XX Informational Custom Response
2XX Success Custom Response
3XX Redirection Custom Response
4XX Client Error Custom Response
5XX Server Error Custom Response


Operation/Event Response Codes

Security validations

In the case of invalid authentication credentials or submission format, a (401) Unauthorized response is returned.

Before Operation event

If you alter the $.Result.Data.HTTPContext.StatusCode to anything (even 200) within this event’s custom logic, a response with the code will be returned and the request flow will cease.

Authentication event

The OperationEvents_Authenticate event is set by default to return a result value of $.Result.Data.HtttpContext.User.IsAuthenticated which triggers a (401) Unauthorized response.

Therefore, you must add custom logic in this event to set the value of $.Result.Data.HtttpContext.User.IsAuthenticated in the case of HTTP Basic and API Key security schemes.

Execute Operation

By default, all operations have a response Status Code of (200) OK unless set otherwise or an exception is thrown within the operation’s logic, in that case a (500) Internal Server Error is returned.

If you want to return a custom response code like 201 or 404 then you are also able to configure it in your operation logic. This is done by adding the relevant HTTP Response Codes to your API definition, and then setting the $.Result.Data.HTTPContext.StatusCode property within the operation to the code you require. Following this you can set the relevant response body.

After Operation event

You are able to override the HTTPContext.StatusCode of the operation in this event, you are able to set it as any response code.

Supported Media Types

Input parameters are deserialized into the relevant TYP.

The following data/media types are supported in requests:

Input Data Type Location Accepted Content-Type Header
Basic Data Type (integer, string etc) URL, Query, Body - application/json
- text
- application/xml
Object , List Body - application/json
- application/xml
Binary / Filestream Body - application/octet-stream


If you attempt to make a request with an incorrect content-type header or an unsupported content-type, then a (415) Unsupported Media Type response will be returned automatically.

Warning:

The steps provided in this explanation are based on Linx before release 6.4.0.

In Linx 6.4.0 and higher there is a Return function in the Linx plugin that must be used for setting the value of a function's result. The SetValue function and $.Result cannot be used for this purpose anymore.

Go here for details of the Return function.


Get Started - Hello World

Before and After operation events

Working with inputs

Handling responses

Securing your API

Deploying and common issues

Generating API documentation

Sample solution: CRUD and file operations

Sample

View our sample solution on GitHub.