IR
irwinrodriguez.dev
Back to docs

API Reference

Complete reference of all public classes, methods and properties in FoxServer.

ApiController

Base class that all controllers must inherit from. Provides access to JSON utilities, JWT generation, logging and the endpoint lifecycle.

Response helpers

Property / MethodTypeDescription
newObject(fields)ObjectCreates a dynamic VFP object. fields is a comma-separated list of names.
ToJson(obj)StringSerializes a VFP object to a JSON string.
FromJson(json)ObjectDeserializes a JSON string to a VFP object.
GenerateJWT(user)StringGenerates a signed JWT token for the given user.
GetUserIdFromToken(req)StringExtracts the user ID from the request's JWT token.
LogInfo(msg)VoidWrites an INFO message to the server log.
LogError(msg)VoidWrites an ERROR message to the server log.
QueueWebhook(url, secret, evt)VoidQueues a webhook event for async delivery.
GetServerMetrics()ObjectReturns the server metrics object (uptime, requests, memory...).

Lifecycle hooks

Property / MethodTypeDescription
BeforeEndpoint(req, res)BooleanRuns before each endpoint. Return .F. to abort the request.
AfterEndpoint(req, res)VoidRuns after each endpoint. For resource cleanup.
BeforeRequest(req, res)BooleanProject-level hook. Before any routing.
AfterResponse(req, res)VoidProject-level hook. After the response is sent.

FoxServerRequest

Object that encapsulates all information about the incoming HTTP request. Available as the req parameter in all endpoints.

Properties

Property / MethodTypeDescription
methodStringGET, POST, PUT, PATCH, DELETE, HEAD
urlUriFull request URL as a Uri object
pathStringPath without query string. E.g.: /api/v1/products
paramsObjectURL parameters. E.g.: params.id from route /{id}
queryObjectQuery string parameters. E.g.: query.page from ?page=2
headersDictionaryHTTP headers. Case-insensitive access. E.g.: headers.Authorization
bodyStringRequest body as plain text (raw)
jsonObjectParsed JSON body. Only available if Content-Type: application/json
contentTypeStringContent-Type header value
remoteIPStringClient IP address
schemeString"http" or "https"

Methods

* Get URL param with fallback
lcId = req.GetParam("id", "")

* Check if a header was sent
IF req.HasHeader("X-Api-Key")
    lcKey = req.headers["X-Api-Key"]
ENDIF

* Safe JSON access (check before reading nested)
IF !ISNULL(req.json) AND !ISNULL(req.json.address)
    lcCity = req.json.address.city
ENDIF

FoxServerResponse

Object to build and send the HTTP response. Available as the res parameter in all endpoints. All methods are chainable (return res).

Property / MethodDescription
status(code)Sets the HTTP status code (200, 201, 400, 401, 404, 500...)
json(jsonStr)Sends JSON body. Sets Content-Type: application/json automatically.
send(text)Sends plain text or HTML as body.
header(key, value)Adds or overwrites a response header. Chainable.
location(url)Sets the Location header. Use with status(301) or status(302) for redirect.
sendFile(path, disp)Sends a file. disp can be "inline" (display in browser) or "attachment" (force download).

Example

* Standard success response
res.status(200).json(THIS.ToJson(loResult))

* Created with location header
res.status(201)
   .header("Location", "/api/v1/users/" + lcNewId)
   .json(THIS.ToJson(loResult))

* Error response
res.status(400).json('{"error":"Name is required"}')

* File download
res.status(200)
   .header("Content-Disposition", 'attachment; filename="report.pdf"')
   .sendFile("C:\reports\report.pdf", "attachment")

ApiController — Detailed methods

Object and JSON management

Property / MethodDescription
NewObject(fields) Creates a VFP object with properties initialized to NULL. fields is a comma-separated list: "status,data,message".
NewObjectFromCursor(cursor, session) Creates a VFP object mirroring a cursor structure. Useful for creating templates based on table schemas.
ToJson(obj) Serializes a VFP object to a JSON string via JSONFox.
ParseJson(jsonStr) Deserializes a JSON string to a VFP object via JSONFox.
TableToJson(cursor, currentRow) Converts a cursor to JSON. currentRow=.T. returns the current record as an object; .F. returns all records as an array.
TableToJsonObject(cursor, currentRow, session) Like TableToJson but returns a VFP object collection instead of a JSON string. Useful for manipulating data before final serialization.
MasterToJSON(master, detail, expr, attr) Generates hierarchical master-detail JSON. expr is the join condition (e.g. "master.id = detail.master_id"), attr is the detail array name in the output JSON.
* Ejemplo: maestro-detalle con MasterToJSON
SELECT id, fecha, cliente FROM pedidos INTO CURSOR curPedidos
SELECT id, pedido_id, producto, cantidad FROM lineas INTO CURSOR curLineas
lcJson = THIS.MasterToJSON("curPedidos", "curLineas", "curPedidos.id = curLineas.pedido_id", "lineas")
res.status(200).json(lcJson)

Text and formatting utilities

Property / MethodDescription
Format(template, p0..p10) Substitutes {0}, {1}, ... placeholders in the template string. Similar to C# String.Format.
EscapeCharsToJSON(text) Escapes special characters for safe use in JSON strings.
EscapeCharsToHTML(text) Escapes special characters for use in HTML output.
Content(req, source) Serializes source (cursor, object or string) to the format requested by the client via Accept header or ?format= (json, xml, csv).
TableToXml(cursor, currentRow) Converts a cursor to XML.
TableToCsv(cursor, currentRow) Converts a cursor to CSV.

Date, encoding and identifier utilities

Property / MethodTypeDescription
NewGuid() String Generates a GUID without braces or dashes. Use for all PKs.
DTOUNX(dt, useMsec) Number Converts a VFP DateTime to a Unix timestamp. useMsec=.T. returns milliseconds.
UNXTOD(timestamp) DateTime Converts a Unix timestamp (seconds or milliseconds) to a VFP DateTime.
Base64URLEncode(input) String Encodes to Base64URL (used in JWTs and safe URLs).
Base64URLDecode(input) String Decodes from Base64URL.
* Conversiones de fecha
lnTs = THIS.DTOUNX(DATETIME(), .F.)   && segundos
ldFecha = THIS.UNXTOD(1716825600)

* Identificadores
lcId = THIS.NewGuid()   && "a1b2c3d4e5f647g8h9i0j1k2l3m4n5o6"

* Formato de mensajes
lcMsg = THIS.Format("Usuario {0} accedio a {1} desde {2}", lcUser, lcUrl, lcIp)

Lifecycle and resources

Property / MethodDescription
Initialize() Runs automatically when an instance is created. Configures cPath, loads JSONFox and ApiService.
LoadJsonFox() Loads JSONFox.app if not yet available. Called internally by Initialize().
GetGlobalResource(name) Gets a shared global resource (connections, configs) through the application lifecycle.
SetWorkingDirectory(path) Sets cPath and calls Initialize(). Useful for testing outside the FoxServer cycle.
CleanUp() / Release() / Dispose() Releases resources at the end of the controller lifecycle. Invoked automatically by FoxServer.

FoxServerRequest — Detailed methods

Property / MethodDescription
GetHeader(key, default) Returns the value of the specified HTTP header. Returns default if not present.
GetParam(key, default) Returns a URL route parameter (e.g. {id}). Returns default if not present.
GetQuery(key, default) Returns a query string parameter (?key=value). Returns default if not present.
GetQueryParams() Returns all query parameters as a FoxServerTupleDictionary.
HasJsonBody() .T. if the request has a valid, parsed JSON body. Check before accessing req.json.*.
GetRawBody() Returns the raw unparsed request body. Required for webhook signature verification.
GetFormField(key, default) Returns the value of a multipart or urlencoded form field.
HasFormField(key) .T. if the form field exists in the request.
File(field) Returns the object for a file uploaded via multipart. Exposes FileName and SaveToFile(path).
Files(field) Returns a collection of files uploaded under the same field name.
* Leer headers y params
lcToken = req.GetHeader("Authorization", "")
lcId    = req.GetParam("id", "")
lcPage  = req.GetQuery("page", "1")

* Verificar body antes de acceder
IF req.HasJsonBody()
    lcEmail = req.json.email
ELSE
    res.status(400).json('{"error":"JSON body required"}')
    RETURN
ENDIF

* Subir archivo
loFile = req.File("avatar")
IF !ISNULL(loFile)
    loFile.SaveToFile(THIS.cPath + "uploads\" + loFile.FileName)
ENDIF

* Webhook: raw body para HMAC
lcRaw = req.GetRawBody()
lcSig = req.GetHeader("X-Signature", "")

Collections

FoxServerTupleDictionary

Key-value dictionary used for Headers, Params and Query. Case-insensitive access.

Property / MethodDescription
CountNumber of entries.
GetKey(n)Key at position n (1-based).
GetValue(n)Value at position n.
Contains(key).T. if the key exists.
GetValueByKey(key)Value by key name.
* Iterar todos los query params
loParams = req.GetQueryParams()
FOR lnI = 1 TO loParams.Count
    lcKey = loParams.GetKey(lnI)
    lcVal = loParams.GetValue(lnI)
    THIS.LogInfo(THIS.Format("Param {0}={1}", lcKey, lcVal))
ENDFOR

FoxServerTuple

Simple key-value pair. Internal component of FoxServerTupleDictionary.

Property / MethodDescription
KeyKey name.
ValueAssociated value.

Next: FAQ →