Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Http.RestServer

Feature notes: HTTPS application layer notes (HTTP/1.1, h2, h3)

Classes, interfaces and records

classeRESTServerError

inherits from Exception

(no public members)

interfaceiRestRequest

(no public members)

interfaceiRestResponse

(no public members)

interfaceiRestRequest

ONE MATCHED REST REQUEST, as a handler sees it: the template captures, the parsed JSON body, the authenticated principal, and the underlying iHttpRequest for everything else (headers, cookies, session, the TLS facts). Valid ONLY during the handler call, like the request it wraps.

function GetHttp: iHttpRequest; function GetJson: tJsonValue; function GetPrincipal: string; function GetParamCount: Integer; function GetParamName(aIndex: Integer): string; function GetParamByName(const aName: string): string; function QueryValue(const aName: string; const aDefault: string = ''): string;
One query-string value, percent-decoded, with '+' read as space - the form convention every REST API uses. The FIRST value wins when a key repeats; a pair that fails decoding is discarded. This is a convenience over Http.Query, which stays raw for the applications the core warns about; names are compared case-sensitively.
property Http: iHttpRequest read GetHttp;
The wrapped request - method, path, headers, cookies, session, Connection (the TLS facts, including the mTLS peer).
property Json: tJsonValue read GetJson;
The request body, already validated and parsed - nil when the request had no body. A handler never sees a malformed body: the dispatcher has already answered 415 (not JSON) or 400 (JSON that does not parse). The tree belongs to the REQUEST - do not free it and do not keep it past the call.
property Principal: string read GetPrincipal;
Whatever the Authenticate seam reported for this request - a user name, a token subject, a certificate key. '' when no authentication is configured, or when the seam allowed without naming anyone.
property ParamCount: Integer read GetParamCount; property ParamNames[aIndex: Integer]: string read GetParamName;
Capture names, in template order.
property Params[const aName: string]: string read GetParamByName; default;
A template capture by name, percent-decoded: for '/orders/{id}' against '/orders/17%2F3', Params['id'] is '17/3' - the decode happens AFTER the path was split, which is what keeps an encoded '/' data rather than structure. '' for a name the template does not capture. The default property, so aRequest['id'] works.

interfaceiRestResponse

THE ANSWER, with the JSON conveniences a REST handler wants. Everything still lands on the wrapped iHttpResponse - reachable as Http for the cases these helpers do not cover (extra headers, files). Every helper SETS THE STATUS EXPLICITLY, so there is no promotion ambiguity: what you send is what goes out.

function GetHttp: iHttpResponse; procedure SendJson(aJson: tJsonValue; aStatus: Integer = 200; aOwns: Boolean = True);
The JSON answer: serialises aJson, sets content-type application/json and the status. aOwns=True (the default) frees aJson before returning, so SendJson(BuildAnswer) leaks nothing; pass False to keep a tree you are reusing. nil aJson sends an empty body, which with the default 200 is a bare acknowledgement.
procedure SendCreated(const aLocation: string; aJson: tJsonValue = nil; aOwns: Boolean = True);
201 with a lowercase location header - the REST answer to "I made the thing, here is where it lives". aJson (optional) is the representation, handled as in SendJson.
procedure SendNoContent;
204: done, nothing to say. The usual answer to DELETE and to a PUT that changed nothing the client needs back.
procedure SendProblem(aStatus: Integer; const aTitle: string = ''; const aDetail: string = '');
An RFC 9457 problem: application/problem+json carrying status, title and detail. aTitle '' takes the standard reason phrase for the code. This is the same shape the dispatcher itself answers errors with, so an API built on it fails uniformly. KEEP aDetail FOR THE CLIENT'S EYES: nothing here should carry an exception message or anything else about the server's insides.
property Http: iHttpResponse read GetHttp;
The wrapped response, for everything else - repeatable headers via Headers.Add, files via SendFile/SendFileRange, non-JSON bodies.

interfaceiRestHandler

WHAT AN APPLICATION IMPLEMENTS - the REST-typed sibling of iHttpRequestHandler, registered per method + template with AddRoute. One instance serves every connection, so it must be safe to call from several threads at once; both arguments die when the call returns. Raising is safe: the dispatcher answers a generic 500 problem and reports the real error to OnRequestError.

procedure HandleRest(const aRequest: iRestRequest; const aResponse: iRestResponse);

interfaceiRestIdempotencyStore

THE IDEMPOTENCY SEAM - the server-side half of the client's IdempotencyHeader. The dispatcher consults it for every UNSAFE request (anything but GET/HEAD/OPTIONS/TRACE) that carries a key, scoping the key by method and path so one client key cannot collide across endpoints.

The contract is a reservation: BeginRequest answering rivNew RESERVES the key, and the dispatcher then always either CompleteRequest (the answer is stored and replayed to duplicates) or AbandonRequest (the reservation is dropped and a retry executes afresh). 5xx answers are ABANDONED, never stored - a transient failure must not become the key's permanent answer.

Implementations MUST be safe to call from several threads at once; the bundled one (NewRestIdempotencyStore) locks itself, expires entries on a TTL and evicts the oldest completed entry past its cap.

function BeginRequest(const aKey: string; out aStatus: Integer; out aContentType: string; out aBody: TBytes): tRestIdempotencyVerdict; procedure CompleteRequest(const aKey: string; aStatus: Integer; const aContentType: string; const aBody: TBytes); procedure AbandonRequest(const aKey: string);

classtRestRoute

ONE ROUTE: a method, a parsed template, a handler. Built and owned by the dispatcher; declared here only because the dispatcher's route list needs the type. Application code never touches it.

constructor Create(const aMethod, aTemplate: string; const aHandler: iRestHandler; aAuthExempt: Boolean); function MatchesSegments(const aSegs: array of string): Boolean;
True when the raw path segments fit this template: counts equal, literals equal (raw, case-sensitive), and every capture position holds a NON-EMPTY segment - '/orders/' does not match '/orders/(id)'.
function SameShape(const aOther: tRestRoute): Boolean;
Same method and same segment shape - capture names aside - so AddRoute can replace rather than shadow.
property Method: string read fMethod; property AuthExempt: Boolean read fAuthExempt; property Handler: iRestHandler read fHandler;

classtRestDispatcher

inherits from TInterfacedObject

implements iHttpRequestHandler

THE ENGINE. An iHttpRequestHandler that owns the route table and runs the pipeline documented at the top of the unit. Transport-free: tests drive HandleRequest with hand-built tHttpServerRequest/tHttpServerResponse objects and no socket exists anywhere.

LIFETIME: refcounted. The component keeps one interface reference for the engine's whole life and hands the same reference to the router's prefix mount; nothing ever calls Free on it. Code using the engine directly should do the same - hold it as iHttpRequestHandler (or assign it to one immediately) and let the last reference free it.

Routes are NOT locked: register them before the server goes Active. The callbacks fire with EventSender as Sender - the component sets itself.

constructor Create; destructor Destroy; override; procedure AddRoute(const aMethod, aTemplate: string; const aHandler: iRestHandler; aAuthExempt: Boolean = False);
Registers aHandler for aMethod + aTemplate, e.g. AddRoute('GET', '/orders/(id)', lOrders) - with the capture in braces, which this comment cannot show. Full description »
procedure AddRouteEvent(const aMethod, aTemplate: string; aEvent: tRestRequestEvent; aAuthExempt: Boolean = False);
AddRoute for an event instead of an interface.
procedure ClearRoutes; procedure HandleRequest(const aRequest: iHttpRequest; const aResponse: iHttpResponse);
iHttpRequestHandler - the pipeline. Public so a test can call it directly with hand-built request/response objects.
property BasePath: string read fBasePath write SetBasePath;
The mount this dispatcher answers under, stripped before templates are tried; '' (or '/') means the templates see the whole path. Kept in step with the component's published BasePath by its mount logic.
property EventSender: TObject read fEventSender write fEventSender;
What the callbacks receive as Sender; the component passes itself.
property OnAuthenticate: tRestAuthenticateEvent read fOnAuthenticate write fOnAuthenticate; property OnError: tRestErrorEvent read fOnError write fOnError; property IdempotencyStore: iRestIdempotencyStore read fIdempotencyStore write fIdempotencyStore;
nil disables idempotency handling - keys then pass through to handlers untouched.
property IdempotencyHeader: string read fIdempotencyHeader write fIdempotencyHeader; property AuthChallenge: string read fAuthChallenge write fAuthChallenge;

classTsmCustomRESTServer

inherits from TComponent

THE COMPONENT. Drop one, point Protocol at either HTTPS protocol component (the property is typed at their common base), register routes, done - the canonical wiring shares ONE router between TsmHTTPSv1dot1 and TsmHTTPSv2, so mounting on either component's router serves both wires.

The association binds in Loaded, exactly like Protocol's own Server reference: during DFM streaming the referenced component may not exist yet. Runtime assignment binds immediately. MountOn is the escape hatch for a router that belongs to no component - a test, a hand-built server.

The seams are virtual-method-plus-event pairs, the same contract as TsmCustomRESTClient: subclass and override, or drop an instance and assign the event - both work, and an override that calls inherited keeps the event working.

constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddRoute(const aMethod, aTemplate: string; const aHandler: iRestHandler; aAuthExempt: Boolean = False);
Route registration, forwarded to the engine - see tRestDispatcher. Register before the server goes Active. » member page
procedure AddRouteEvent(const aMethod, aTemplate: string; aEvent: tRestRequestEvent; aAuthExempt: Boolean = False); procedure MountOn(const aRouter: iHttpRouter);
The runtime escape hatch: mounts on aRouter directly, for a router that belongs to no protocol component. Raises eRESTServerError when the router has no prefix mounts (iHttpPrefixRouter) - the library's own (NewHttpRouter) always does. Unmounts from wherever it was first, so moving a REST server is one call. » member page
procedure Unmount;
Removes the mount, wherever it is. Safe to call unmounted. » member page
property Dispatcher: tRestDispatcher read fDispatcher;
The engine, for what the published surface does not carry - EventSender aside (the component owns that). » member page
property IdempotencyStore: iRestIdempotencyStore read GetIdempotencyStore write SetIdempotencyStore;
The idempotency store. The constructor installs the bundled in-memory one (NewRestIdempotencyStore, one hour TTL, 10000 entries), so a client sending keys is honoured out of the box; assign nil to disable, or your own iRestIdempotencyStore to persist. Runtime only - an interface is nothing the Object Inspector can carry. » member page
property Protocol: TsmCustomHTTPSProtocol read fProtocol write SetProtocol;
Either HTTPS protocol component - the property is typed at their shared base. Assigning mounts the dispatcher on that component's Router at BasePath (in Loaded when streamed); clearing unmounts. With the canonical shared-router wiring, one assignment serves both wires. » member page
property BasePath: string read fBasePath write SetBasePath;
The subtree this REST server owns, e.g. '/api'. Exact routes and other mounts outside it are untouched; templates are relative to it. '/' claims every path the exact routes do not. Default '/api'. » member page
property IdempotencyHeader: string read GetIdempotencyHeader write SetIdempotencyHeader;
The request header carrying the client's idempotency key. The default matches TsmRESTClient's default, so the pair works unconfigured. » member page
property AuthChallenge: string read GetAuthChallenge write SetAuthChallenge;
What a 401 carries in its www-authenticate header - the scheme the API expects. Default 'Bearer'. » member page
property OnAuthenticate: tRestAuthenticateEvent read fOnAuthenticate write fOnAuthenticate; property OnRequestError: tRestErrorEvent read fOnRequestError write fOnRequestError;

classTsmRESTServer — component reference

inherits from TsmCustomRESTServer

(no public members)

Types (enumerations, sets, aliases)

proctRestRequestEvent

The event way to answer a route - AddRouteEvent. A DISTINCT name rather than an AddRoute overload, deliberately: Delphi cannot resolve a bare method reference across an interface-vs-method-pointer overload (E2250).

  tRestRequestEvent = procedure (Sender: TObject;
                                 const aRequest: iRestRequest;
                                 const aResponse: iRestResponse) of object;

proctRestAuthenticateEvent

THE AUTH SEAM. Fired for every matched route that is not AuthExempt, BEFORE the body is parsed - an unauthenticated peer's body is never worth parsing. aAllow ARRIVES False: the moment a policy is wired in, the default is deny, and the handler's job is to prove the request in. Set aPrincipal to whatever names the caller - it travels to the handler as aRequest.Principal. Everything needed for the decision is on aRequest: the authorization header via Http.Headers, the mTLS peer via Http.Connection (authorize on PeerIssuer + PeerSerialNumber, as that interface documents - not on a DN string). A refusal answers 401 with a lowercase www-authenticate carrying AuthChallenge.

  tRestAuthenticateEvent = procedure (Sender: TObject;
                                      const aRequest: iRestRequest;
                                      var aAllow: Boolean;
                                      var aPrincipal: string) of object;

proctRestErrorEvent

A handler raised. aError is the real exception - log it here; the wire got a 500 problem with a generic detail and nothing else. Runs on the I/O thread that ran the handler, so treat it as logging, not as work.

  tRestErrorEvent = procedure (Sender: TObject;
                               const aRequest: iRestRequest;
                               aError: Exception) of object;

enumtRestIdempotencyVerdict

What the store found for a key when a request began.

  tRestIdempotencyVerdict = (rivNew,          { never seen - execute and store  }
                             rivInFlight,     { executing right now - 409       }
                             rivReplay,       { completed - replay the answer   }
                             rivOverloaded);  { store full of in-flight work    }

Routines