Přeskočit na hlavní obsah

IApiEndpoint (27.1)

By implementing the IApiEndpoint interface, you can define custom HTTP endpoints that execute backend logic in Alvao. Depending on the value of the Visibility property, an endpoint can be called from Custom JavaScript running in WebApp, by external systems through REST API, or through both invocation paths. Both invocation methods use the same IApiEndpoint implementation.

Creating an API endpoint​

In the application, create a new script using the IApiEndpoint template. Implement the endpoint according to the required functionality. Each endpoint defines the following property:

Route​

A unique identifier of the endpoint. The route is used as part of the endpoint URL and when invoking the endpoint from Custom JavaScript.

The route:

  • must start with an alphanumeric character
  • can contain alphanumeric characters, periods, underscores, and hyphens
  • must not contain spaces or diacritics
  • can contain up to 64 characters
  • should use camelCase
  • must be unique among scripts implementing IApiEndpoint

Example:

public string Route => "getTicketInfo";

The platform does not validate the route when the script is compiled. It is the application developer's responsibility to use a valid and unique route.

If the route does not meet the required format or is not unique, the resulting behavior is undefined and may be non-deterministic. For example, the request may be routed to an unexpected endpoint, or fail to invoke an endpoint.

Visibility​

Specifies the invocation paths through which the endpoint is available. Example:

public Visibility Visibility => Visibility.Internal;

The following values are available:

  • Internal makes the endpoint available only to Custom JavaScript running in WebApp. The call is executed under the identity of the currently signed-in user.
  • Public makes the endpoint available both to Custom JavaScript running in WebApp and to external systems through REST API.
  • If the endpoint is called through an invocation path that is not allowed by Visibility, the routing layer returns 404 Not Found and does not invoke HandleAsync.

The Visibility property controls only the availability of the endpoint. It does not replace authentication or authorization. The endpoint implementation is responsible for verifying that the caller is allowed to perform the requested operation.

Interface methods​

HandleAsync​

Processes an incoming HTTP request and generates an HTTP response.

Task<HttpResponseMessage> HandleAsync(ApiEndpointEventArgs e);

The ApiEndpointEventArgs parameter contains all information related to the current endpoint invocation.

Parameters​

e.Request Contains the incoming http request. The endpoint can retrieve:

  • the HTTP method from e.Request.Method
  • query parameters from e.RequestUri.Query
  • HTTP headers from e.Request.Headers
  • the request body from e.Request.Content
  • the content type from e.Request.Content?.Headers.ContentType
  • the requested URI from e.Request. RequestUri

The endpoint is responsible for reading and deserializing the request body according to its content type.

e.Response Represents the http response returned to the caller. The endpoint can use it to set:

  • the HTTP status code
  • response headers
  • the content type
  • the response body

The response can contain JSON, XML, HTML, plain text, or another content type supported by the caller.

e.PersonId

The property contains the identifier of the authenticated Alvao user under whose identity the endpoint is executed.

When the endpoint is called from Custom JavaScript, the server obtains the user identity from the authenticated WebApp session. The client does not send PersonId and cannot modify it.

When the endpoint is called through REST API and ALVAO Basic or Entra ID authentication succeeds, PersonId contains the identifier of the authenticated ALVAO user.

If PersonId is null, the endpoint was not authenticated as an Alvao user. The endpoint implementation must perform any authentication required by its integration scenario.

Authentication does not automatically authorize the requested operation. The endpoint should verify that the authenticated user has the permissions required to read or modify the requested data.

e.CancellationToken

A cancellation token for the current HTTP request.

Use this token when calling asynchronous methods. Processing can then be cancelled if the caller aborts the request or the connection is terminated.

Return value

The method returns an HttpResponseMessage describing the HTTP response that will be sent to the caller.

Example

The following endpoint reads ticketId from the query string and returns a JSON response containing the ticket identifier and the identifier of the authenticated user:

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using System.Web;
using Alvao.API.Common;
using Alvao.API.SD;
using Alvao.Apps.API;

public class GetTicketInfoEndpoint : IApiEndpoint
{

public string Route => "GetTicketInfo";
public Visibility Visibility => Visibility.Internal;
public async Task<HttpResponseMessage> HandleAsync(ApiEndpointEventArgs e)

{
// Authentication check

if (e.PersonId == null)
{
e.Response.StatusCode = HttpStatusCode.Unauthorized;
            e.Response.Content = JsonContent.Create(new { code = "Unauthorized", message = "Basic authentication is required." });
            return e.Response;
}

// Input validation

if (!int.TryParse(HttpUtility.ParseQueryString(e.Request.RequestUri.Query)["ticketId"], out int ticketId))

        {
            e.Response.StatusCode = HttpStatusCode.BadRequest;
            e.Response.Content = JsonContent.Create(new { code = "InvalidRequest", message = "Query parameter 'ticketId' is missing or invalid." });
            return e.Response;
        }

var ticket = Ticket.GetById(ticketId);

if (ticket == null)

{
e.Response.StatusCode = HttpStatusCode.NotFound;
            e.Response.Content = JsonContent.Create(new { code = "TicketNotFound", message = $"Ticket {ticketId} was not found." });
            return e.Response;
}

// Checking rights

if (!PersonRights.CanReadTicket(e.PersonId .Value, ticketId))

{
e.Response.StatusCode = HttpStatusCode.Forbidden;
            e.Response.Content = JsonContent.Create(new { code = "Forbidden", message = "You are not allowed to read it." });
            return e.Response;

}
e.Response.Content = JsonContent.Create(new {
            TicketId = ticket.iHdTicketId,
            Name = ticket.sHdTicket,
            Resolved = ticket.dHdTicketResolved

        });
        return e.Response;
}
}

Calling from Custom JavaScript:

const result = await self.callApiEndpoint("GetTicketInfo",
{
method: "GET",
query: {
ticketId: 123
},
headers: {
Accept: "application/json"
}
}
);
console.log(result.ticketId);