Built-in objects
Every Raytha Function gets five ready-made objects: API_V1 to read and write your site's data, CurrentUser and CurrentOrganization for context, Emailer to send mail and HttpClient to call other servers. This page lists them with exact signatures and shows how to use each one from JavaScript.
How the objects behave
- Calls are synchronous. They return when the work is done, not a promise.
- The objects are .NET objects. Their members keep their PascalCase names:
res.Success,res.Result.Items. JavaScript properties on your own objects stay as you write them. - Ids go in as strings and come out as
ShortGuidobjects. Call.ToString()on one to get the 22-character string.String(id)gives"[object Object]". API_V1has no permission checks and no knowledge of who called the function.
API_V1
API_V1 mirrors the REST API at /raytha/api, but it calls the application layer directly. These are all 47 methods. Every pageNumber starts at 1, and pageSize defaults to 50.
// Content items
GetContentItems(string contentTypeDeveloperName, string viewId = "", string search = "", string filter = "", string orderBy = "", int pageNumber = 1, int pageSize = 50)
GetDeletedContentItems(string contentTypeDeveloperName, string search = "", string orderBy = "", int pageNumber = 1, int pageSize = 50)
GetContentItemById(string contentItemId)
CreateContentItem(string contentTypeDeveloperName, bool saveAsDraft, string templateId, IDictionary<string, object> content)
EditContentItem(string contentItemId, bool saveAsDraft, IDictionary<string, object> content)
EditContentItemSettings(string contentItemId, string templateId, string routePath)
UnpublishContentItem(string contentItemId)
DeleteContentItem(string contentItemId)
GetRouteByPath(string routePath)
// Content types
GetContentTypes(string search = "", string orderBy = "", int pageNumber = 1, int pageSize = 50)
GetContentTypeByDeveloperName(string contentTypeDeveloperName)
// Media items
GetMediaItems(string search = "", string orderBy = "", int pageNumber = 1, int pageSize = 50)
GetMediaItemUrlByObjectKey(string objectKey)
// User groups
GetUserGroups(string search = "", string orderBy = "", int pageNumber = 1, int pageSize = 50)
GetUserGroupById(string userGroupId)
CreateUserGroup(string developerName, string label)
EditUserGroup(string userGroupId, string label)
DeleteUserGroup(string userGroupId)
// Users (public users only; admin accounts are refused)
GetUsers(string search = "", string orderBy = "", int pageNumber = 1, int pageSize = 50)
GetUserById(string userId)
CreateUser(string emailAddress, string firstName, string lastName, bool sendEmail, dynamic userGroups)
EditUser(string userId, string emailAddress, string firstName, string lastName, dynamic userGroups)
DeleteUser(string userId)
ResetPassword(string userId, bool sendEmail, string newPassword)
SetIsActive(string userId, bool isActive)
// Templates
GetWebTemplates(string search = "", string orderBy = "", int pageNumber = 1, int pageSize = 50)
GetWebTemplateById(string webTemplateId)
// Functions
ExecuteRaythaFunction(string developerName, string requestMethod, string queryJson, string payloadJson)
// Site pages
GetSitePages(string search = "", string orderBy = "", int pageNumber = 1, int pageSize = 50)
GetSitePageById(string sitePageId)
CreateSitePage(string title, bool saveAsDraft, string templateId)
EditSitePage(string sitePageId, string title, bool saveAsDraft, string templateId)
EditSitePageSettings(string sitePageId, string routePath)
PublishSitePage(string sitePageId)
UnpublishSitePage(string sitePageId)
DeleteSitePage(string sitePageId)
// Navigation menus
GetNavigationMenus(string search = "", string orderBy = "", int pageNumber = 1, int pageSize = 50)
GetNavigationMenuById(string navigationMenuId)
GetNavigationMenuByDeveloperName(string developerName)
CreateNavigationMenu(string label, string developerName)
EditNavigationMenu(string navigationMenuId, string label)
DeleteNavigationMenu(string navigationMenuId)
// Navigation menu items
GetNavigationMenuItemsByNavigationMenuId(string navigationMenuId)
GetNavigationMenuItemById(string navigationMenuItemId)
CreateNavigationMenuItem(string navigationMenuId, string label, string url, bool isDisabled, bool openInNewTab, string cssClassName, string parentNavigationMenuItemId)
EditNavigationMenuItem(string navigationMenuItemId, string navigationMenuId, string label, string url, bool isDisabled, bool openInNewTab, string cssClassName, string parentNavigationMenuItemId)
DeleteNavigationMenuItem(string navigationMenuItemId, string navigationMenuId)
Return values
Query methods return an object with Success, Error and Result. List queries put an Items collection and a TotalCount in Result. Command methods (create, edit, delete) return the same shape, and Result is the id of the record. A validation failure does not throw: Success is false and Error holds the messages joined with ;. Check it after every write. A malformed id, or an id that does not exist, throws, and you can catch it with try and catch.
Reading content items
A list's Items is a .NET collection. Loop over it with for...of. An item's PublishedContent is a dictionary of field values. Read a field with .Item("name") and check for it with .ContainsKey("name"). Dot access such as content.title is undefined. Each field value has Value (the typed value), Text (a display string) and HasValue.
function get(query) {
var res = API_V1.GetContentItems("posts", "", "", "IsPublished eq 'true'", "CreationTime desc", 1, 10);
if (!res.Success) {
return new StatusCodeResult(500, res.Error);
}
var out = [];
for (var item of res.Result.Items) {
var content = item.PublishedContent;
out.push({
id: item.Id.ToString(), // ShortGuid -> string
title: item.PrimaryField,
path: item.RoutePath,
rank: content.ContainsKey("rank") ? content.Item("rank").Value : null,
tags: content.ContainsKey("tags") ? content.Item("tags").Text : ""
});
}
return new JsonResult({ total: res.Result.TotalCount, items: out });
}
A number field's Value reaches JavaScript as a number. A multiple select field's Value is a .NET string array: use .Length and index it with [0]. The filter and orderBy strings use the same syntax as the REST API. See Filtering. Unlike the public site, GetContentItems returns drafts and unpublished items too, so add IsPublished eq 'true' when you build a public feed.
Writing content items
var POST_TEMPLATE_ID = "1vVCcIYeeE-dMQjbYGq_ng";
function get(query) {
var created = API_V1.CreateContentItem("posts", false, POST_TEMPLATE_ID, {
title: "Hello",
rank: 5,
featured: true,
published_on: "2026-10-02",
tags: JSON.stringify(["news", "docs"]), // multiple select: a JSON string, not an array
faq: JSON.stringify([{ question: "Why?", answer: "Because." }]) // repeater: a JSON string of rows
});
if (!created.Success) {
return new StatusCodeResult(400, created.Error); // messages are joined with ";"
}
var id = created.Result.ToString();
var edited = API_V1.EditContentItem(id, false, { title: "Hello again", rank: 6 });
return new JsonResult({ id: id, edited: edited.Success });
}
templateIdis required when you create. It must be a web template in the active theme that has access to the content type.contentis a JavaScript object keyed by field developer name. Value formats are the same as in the REST API. See Content items.- Pass multiple select and repeater values as JSON strings, as in the example. A JavaScript array or object nested inside
contentcannot be read by the .NET side, and the call blocks until the function times out. EditContentItemreplaces the whole content. Send every field you want to keep.- Creating or editing raises the content item events, so it can trigger other functions. See Content event triggers.
CurrentUser
The person who made the request, from the Raytha session cookie. An anonymous visitor has IsAuthenticated === false and empty names. API keys do not apply here. In a content event function there is no request, so CurrentUser is never authenticated.
| Member | Type | Meaning |
|---|---|---|
IsAuthenticated | bool | Signed in. |
UserId | ShortGuid or null | Account id. Call .ToString(). |
FirstName, LastName, FullName | string | Empty when anonymous. |
EmailAddress | string | Empty when anonymous. |
IsAdmin | bool | The account is an administrator. |
Roles | string[] | Administrator role names. |
UserGroups | string[] | Developer names of the user's groups. |
AuthenticationScheme | string | Developer name of the scheme used to sign in, for example jwt. |
SsoId | string | The identity provider's id for the person, if any. |
RemoteIpAddress | string | The client address. Correct behind a proxy only when TRUSTED_PROXIES is set. |
LastModificationTime | DateTime or null | When the account last changed. |
ImpersonatorId, ImpersonatorEmailAddress | ShortGuid or null, string | Set while an admin impersonates the account. |
CurrentOrganization
| Member | Type | Meaning |
|---|---|---|
OrganizationName | string | Site name. |
WebsiteUrl | string | Public URL from settings. It may end in a slash. |
PathBase | string | The sub-path the app is served under. Empty at the root. |
TimeZone, DateFormat | string | Organization settings. |
SmtpDefaultFromAddress, SmtpDefaultFromName | string | Default sender, for EmailMessage.From. |
EmailAndPasswordIsEnabledForAdmins, EmailAndPasswordIsEnabledForUsers | bool | Whether that scheme is on. |
HomePageId, HomePageType | ShortGuid or null, string | The home page target. |
ActiveThemeId | ShortGuid | The active theme. |
RedirectWebsite | string | Set when the site redirects to another URL. |
AuthenticationSchemes | collection | Configured schemes: label, developer name, sign-in and sign-out URLs, and the enabled toggles. JwtSecretKey and SamlCertificate are not included. |
ContentTypes | collection | Content types with their fields. |
Returning CurrentOrganization publishes the site name, URLs and scheme labels. It does not publish a JWT signing secret or a SAML certificate, because a function never receives those.
Emailer and EmailMessage
Create a message with the static EmailMessage.From and send it with Emailer.SendEmail. It uses the SMTP settings from Sending emails.
// EmailMessage.From(subject, content, to, fromEmailAddress, fromName)
var message = EmailMessage.From(
"Welcome",
"<p>Thanks for signing up.</p>",
"[email protected]",
CurrentOrganization.SmtpDefaultFromAddress,
CurrentOrganization.SmtpDefaultFromName
);
Emailer.SendEmail(message);
The content is sent as HTML. The message has one recipient. Assigning properties on new EmailMessage(), such as To or Subject, fails with "Invalid property assignment", so always build messages with From. Escape any visitor-supplied text you put in the content. There are no attachments, Cc or Bcc from JavaScript.
HttpClient
A synchronous wrapper over .NET's HttpClient. Each method returns the response body as a string.
Get(string url, IDictionary headers = null)
Post(string url, IDictionary headers = null, IDictionary body = null, bool json = true)
Put(string url, IDictionary headers = null, IDictionary body = null, bool json = true)
Delete(string url, IDictionary headers = null)
var body = HttpClient.Post(
"https://api.example.com/v1/orders",
{ "Authorization": "Bearer " + token },
{ sku: "A-1", quantity: 2 }
);
var order = JSON.parse(body);
- With
jsontrue, the body is sent asapplication/json; charset=utf-8. Withfalseit is sent asapplication/x-www-form-urlencoded. - A status outside 200 to 299 throws an exception with the message
Request failed with status code .... Wrap calls intryandcatch. - Pass arguments by position.
HttpClient.Post(url, headers=h, body=b)works only because JavaScript evaluates the assignments in order; it creates globals and is not named parameters. - Requests stop when the function times out. Localhost and private addresses are blocked unless
ALLOW_INTERNAL_URL_IMPORTS=true.
.NET types
These are available as globals: Guid, ShortGuid, Convert, DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan, Math, decimal, char, Random, Uri, UriBuilder, Regex, StringBuilder, Encoding, StringComparison, Stopwatch, BitConverter, Tuple, ValueTuple, Enumerable, JavaScriptExtensions, and the generic types List, Dictionary, KeyValuePair, HashSet, Queue, Stack. Examples that work:
var id = Guid.NewGuid().ToString();
var sid = ShortGuid.NewGuid().ToString();
var yesterday = DateTime.UtcNow.AddDays(-1).ToString("yyyy-MM-dd");
var ok = Regex.IsMatch("abc123", "\\d+");
var b64 = Convert.ToBase64String(Encoding.UTF8.GetBytes("hello"));
var safe = Uri.EscapeDataString("a b&c");
var biggest = Math.Max(2, 5);
var list = new List(Guid);
list.Add(Guid.NewGuid());
What is not available
These are all undefined: require, import (no modules), fetch, setTimeout, setInterval, URL, TextEncoder, atob, btoa, structuredClone and crypto. There is no way to compute an HMAC or a hash with the host types. Reflection is blocked: obj.GetType() fails with "Use of reflection is prohibited". console exists, but its output goes nowhere you can read.
Gotchas
Mathis the .NET class. Raytha addsSystem.Mathunder the nameMath, which replaces the JavaScript one.Math.floorandMath.randomareundefined. UseMath.Floor,Math.Round,Math.Max, or(new Random()).Next(10).- Return the fields you mean to show.
new JsonResult(CurrentOrganization)publishes the site name, URLs and scheme labels, and not the JWT secret or the SAML certificate.new JsonResult(CurrentUser)publishes the visitor's own account details, which is safe only if that is what you intend. - Return plain objects from public endpoints. If you return an
API_V1result throughJsonResult, it is written with PascalCase names, and a ShortGuid appears as{"Guid": ..., "Value": ...}. Copy the fields you need into your own object. - Dates.
item.CreationTimeis a .NETDateTime. Use.ToString("o"), nottoISOString(). JavaScriptDatevalues you pass incontentare not converted, so send ISO strings. - Nested functions hold a slot.
ExecuteRaythaFunctionruns another function. The caller keeps its slot while it waits, so withRAYTHA_FUNCTIONS_MAX_ACTIVElow, nested calls can queue behind their own caller. - Existing-item calls in event functions. See Content event triggers.
Next steps
- HTTP request trigger: how a function answers a request.
- Liquid template trigger: calling functions from templates.
- Content items: field value formats shared with
API_V1. - Recipes: complete examples.