### OnStart Implementation Example Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-start A basic implementation of the OnStart function to prepare the environment. ```tlpp #include "tlpp-core.th" #include "tlpp-rest.th" User Function onStart() As Logical Local lOK := .T. As Logical lOK := U_preparaAmbiente() Return lOK ``` -------------------------------- ### VdrCtrl():Start() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/referencia-json Initializes the server using a JSON configuration object. Returns 0 on success, or an error code on failure. ```APIDOC ## VdrCtrl():Start() ### Description Initializes the server based on the provided JSON configuration object. This method is the entry point for starting the server service. ### Parameters - **jConfig** (JsonObject) - Required - A JSON object containing the server configuration, including HTTPSERVER, HTTP_REST, and THREAD_POOL settings. ### Returns - **nResult** (Numeric) - Returns 0 if the server started successfully. Any other value indicates a failure, which can be inspected via `oVdrCtrl:nErr` and `oVdrCtrl:cErr`. ``` -------------------------------- ### Configure Server with Basic Auth in INI Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/authorization Full server configuration example in an INI file including the TlppData security injection. ```ini [HTTPSERVER] Enable=1 Servers=HTTP_SRV ; ... outras chaves ... [HTTP_SRV] ; Injeta a configuração de segurança informando o esquema e a função validadora TlppData='{"Authorization":{"scheme":"basic","OnAuth":"U_onAuthorization"}}' ; ... outras chaves ... ``` -------------------------------- ### GET /totvs/environment Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Endpoint para verificar a versão do ambiente. ```APIDOC ## GET /totvs/environment ### Description Retorna informações sobre a versão, build e patch do AppServer e/ou TLPP em formato JSON. ### Method GET ### Endpoint /totvs/environment (ou /appserver/environment, /tlpp/environment) ``` -------------------------------- ### Implement OnStop Function Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-stop Example implementation of the OnStop function to close the environment. ```tlpp #include "tlpp-core.th" #include "tlpp-rest.th" User Function onStop() As Logical Local lOK := .T. As Logical lOK := U_fechaAmbiente() Return lOK ``` -------------------------------- ### Implement Custom Slave Selection Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-select Example of selecting a specific slave based on its ID. ```advpl #include "tlpp-core.th" #include "tlpp-rest.th" Function u_restGrader(cClassName As Character, cFunctionName As Character, cProgramType As Character) As Integer Local nIndex := -1 As Integer Local aSlaves := oRest:GetThreadPoolSlaves() As Array Local nA := 0 As Integer For nA := 1 To Len(aSlaves) If (aSlaves[nA]:ID == 6) nIndex := nA Exit EndIf Next Return nIndex ``` -------------------------------- ### Enable Soft Mode for OnAllow Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-allow Configure the server to start even if the OnAllow function fails by setting OnAllowSoft to true in the TlppData configuration. ```ini [THREAD_POOL] TlppData={"OnAllowSoft":true} ``` -------------------------------- ### Implement OnAuth Callback Function Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/authorization Example of a user-defined function to validate credentials for Basic Auth. ```tlpp #include "tlpp-core.th" #include "tlpp-rest.th" /* Callback de validação da autenticação Basic. */ User Function onAuthorization(cUser As Character, cPass As Character) As Logical Local lRet := .F. As Logical lRet := (cUser == 'test_user' .And. cPass == 'test_pass') Return lRet ``` -------------------------------- ### GET /tlpp/rest/config Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Endpoint para visualizar e alterar configurações de log e comportamento do REST em tempo de execução. ```APIDOC ## GET /tlpp/rest/config ### Description Permite alterar configurações como rest_log_level, rest_error_full, rest_trace_time, rest_reload_time e rest_log_stringsize sem necessidade de reiniciar o serviço. ### Method GET ### Endpoint /tlpp/rest/config ``` -------------------------------- ### GET /appserver/metrics Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Endpoint de monitoramento de memória do AppServer. ```APIDOC ## GET /appserver/metrics ### Description Endpoint de monitoramento que exige configuração específica no [APP_MONITOR] do appserver.ini. Fornece dados de consumo de memória. ### Method GET ### Endpoint /appserver/metrics ### Parameters #### Query Parameters - **all** (string) - Optional - Retorna o consumo de memória completo. - **memory_resident** (string) - Optional - Filtra o consumo de memória por campo. ``` -------------------------------- ### Implement U_onBlock Function Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-block Example implementation of the U_onBlock function to block or hide specific endpoints and HTTP methods. ```tlpp Function U_onBlock( oList ) Local cEndpoint := '' Local cServiceName := oList:getServiceName() Local nServicePort := oList:getServicePort() Local cThreadPoolName := oList:getThreadPoolName() Local cUserData := oList:getUserData() Local jApis := oList:getApiList() // Bloqueia ou oculta endpoint + método (use conforme necessidade) cEndpoint := '/exemplo1/urn' oList:block( cEndpoint, 'get' ) oList:block( cEndpoint, 'post' ) oList:hide( cEndpoint, 'put' ) cEndpoint := '/exemplo2/urn' oList:block( cEndpoint, 'get' ) Return Nil ``` -------------------------------- ### GET /tlpp/rest/list/service Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Endpoint para descoberta de serviços registrados no ambiente. ```APIDOC ## GET /tlpp/rest/list/service ### Description Retorna um JSON contendo todos os endpoints registrados no ambiente, incluindo annotations e mapeamentos. ### Method GET ### Endpoint /tlpp/rest/list/service ``` -------------------------------- ### GET /tlpp/rest/usage/time Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Endpoint para obter métricas de tempo de execução por entry point. ```APIDOC ## GET /tlpp/rest/usage/time ### Description Fornece métricas de tempo em microssegundos e percentual de uso por entry point, slave e thread pool. O retorno é uma string HTML. ### Method GET ### Endpoint /tlpp/rest/usage/time ``` -------------------------------- ### GET /rest/sample/doc/generate Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/doc-generate An HTTP trigger that invokes the internal tlpp.doc.generate() function to export documentation and save the file on the server. ```APIDOC ## GET /rest/sample/doc/generate ### Description Triggers the generation of API documentation files on the server by calling the internal tlpp.doc.generate() function. ### Method GET ### Endpoint /rest/sample/doc/generate ``` -------------------------------- ### Define a GET route with path parameters Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/annotations Uses the @Get annotation to define a route with a dynamic ID parameter, which is accessed via oRest:getPathParamsRequest(). ```tlpp @Get("users/:id") User Function getUser() Local jParams := oRest:getPathParamsRequest() // jParams["id"] contém o valor capturado na URL Return .T. ``` -------------------------------- ### Configure User Exits in appserver.ini Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/callbacks Example configuration for defining User Exits within the [THREAD_POOL] and [SLAVE] sections of an appserver.ini file. ```ini [THREAD_POOL] UserExits=TP_UEX Slaves=SLAVE_01,SLAVE_02 [TP_UEX] OnBlock=U_OnBlock ;OnAllow=U_OnAllow OnSelect=U_OnSelect OnError=U_OnError [SLAVE_01] UserExits=SLAVES_UEX [SLAVE_02] UserExits=SLAVES_UEX [SLAVES_UEX] OnStart=U_OnStart OnStop=U_OnStop OnSend=U_OnSend OnError=U_OnError ``` -------------------------------- ### Trigger OpenAPI Generation via HTTP Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/doc-generate HTTP GET request to trigger the internal generation of documentation files on the server. ```http GET /rest/sample/doc/generate ``` -------------------------------- ### GET /rest/tlpp/oauth2/token Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/authorization Requests an access token using password grant type. ```APIDOC ## GET /rest/tlpp/oauth2/token ### Description Requests an access token using the password grant type. ### Method GET ### Endpoint https://localhost:47500/rest/tlpp/oauth2/token ### Parameters #### Query Parameters - **grant_type** (string) - Required - Must be 'password' - **username** (string) - Required - User identifier - **password** (string) - Required - User password ### Response #### Success Response (200) - **access_token** (string) - The JWT access token - **refresh_token** (string) - The token used to refresh the access token - **scope** (string) - Token scope - **token_type** (string) - Type of token (Bearer) - **expires_in** (integer) - Expiration time in seconds ``` -------------------------------- ### Teste de requisição HTTP Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/primeiros-passos/quickstart Exemplo de chamada GET para testar o endpoint criado. ```http GET http://localhost:9995/hello ``` -------------------------------- ### Implement custom error handling Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-error Example of logging internal error details and returning a masked JSON response to the client using oRest:SetFault. ```tlpp #include "tlpp-core.th" #include "tlpp-rest.th" /* @param oError Objeto com as propriedades e rastreio da falha de runtime */ Function U_onError( oError As Object ) Local cCodeTrace := U_getCodeTrace() As Character Local cFault := '' As Character // Grava detalhes sensíveis em log interno (não expor ao cliente) U_TrataErro( cCodeTrace, oError:genCode, oError:description ) // Resposta mascarada para o cliente HTTP cFault += '{' cFault += ' "code": "' + cCodeTrace + '",' cFault += ' "message": "Um erro interno ocorreu, por favor informe o administrador de sistema."' cFault += '}' If ( Type('oRest') == 'O' ) oRest:SetFault( cFault ) EndIf Return Nil ``` -------------------------------- ### Dynamic Content-Type Adjustment Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-send Example implementation that detects if the response body is valid JSON and updates the Content-Type header accordingly. ```tlpp #include "tlpp-core.th" #include "tlpp-rest.th" Function U_OnSend() Local cMsgSend := oRest:getBodyResponse() Local jValue := JsonObject():New() Local uRet := Nil If (!Empty(cMsgSend)) uRet := jValue:FromJson(cMsgSend) If (ValType(uRet) == "U") oRest:updateKeyHeaderResponse("Content-Type", "application/json") Else oRest:updateKeyHeaderResponse("Content-Type", "text/plain") EndIf FreeObj(jValue) EndIf Return Nil ``` -------------------------------- ### Request OAuth2 Access Token Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/authorization Use a GET request with query parameters to obtain an access token via password grant. ```http GET https://localhost:47500/rest/tlpp/oauth2/token?grant_type=password&username=josemaria&password=123456abc ``` -------------------------------- ### Definição de endpoint com anotação Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/primeiros-passos/composicao-url Exemplo de uso da anotação @Get para definir um endpoint com parâmetro dinâmico. ```tlpp @Get("users/:id") User Function getUser() // ... Return .T. ``` -------------------------------- ### Criação de endpoint REST Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/primeiros-passos/quickstart Exemplo de função TLPP utilizando a annotation @Get para definir a rota e o método HTTP. ```tlpp #include "tlpp-core.th" #include "tlpp-rest.th" @Get("hello") User Function hello() oRest:setResponse('{"message":"Hello World"}') Return .T. ``` -------------------------------- ### Configure OnStart in SLAVES_UEX Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-start Define the OnStart function in the configuration file under the SLAVES_UEX section. ```ini [SLAVES_UEX] OnStart=U_OnStart ``` -------------------------------- ### User Function onStart() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-start The OnStart function is triggered upon thread creation. It must return a logical value to indicate if the thread should be initialized. ```APIDOC ## User Function onStart() ### Description Executes when the service thread is created, before it enters the pool to receive requests. Use this to initialize context variables or prepare the environment. ### Signature `User Function onStart() As Logical` ### Configuration Configure in the [SLAVES_UEX] section: `OnStart=U_OnStart` ### Return Values - **.T.** (Logical): Thread is created and available in the pool. - **.F.** (Logical): Thread is not created and is terminated immediately. - **Other**: Treated as .F. ### Example ```tlpp #include "tlpp-core.th" #include "tlpp-rest.th" User Function onStart() As Logical Local lOK := .T. As Logical lOK := U_preparaAmbiente() Return lOK ``` ``` -------------------------------- ### Configuração de inicialização via INI Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/primeiros-passos/configuracao Exemplo de configuração no arquivo appserver.ini para disparar a função de inicialização no boot. ```ini [OnStart] Jobs=JOB1 [JOB1] Main=rest.u_start Environment=SEU_ENV ``` -------------------------------- ### OnStart Function Signature Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-start The function must be defined as a User Function returning a Logical value. ```tlpp User Function onStart() As Logical ``` -------------------------------- ### Configuração do appserver.ini Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/primeiros-passos/quickstart Configuração mínima necessária para ativar o servidor HTTP no AppServer. Ajuste o campo Environment para o seu ambiente RPO. ```ini [HTTPSERVER] Enable=1 Servers=HTTP_REST [HTTP_REST] hostname=localhost port=9995 locations=HTTP_ROOT [HTTP_ROOT] Path=/ RootPath=root/web ThreadPool=THREAD_POOL [THREAD_POOL] Environment=ENV MinThreads=1 ``` -------------------------------- ### Configuração de servidor no arquivo INI Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/primeiros-passos/composicao-url Exemplo de configuração de host, porta e path raiz no arquivo de configuração do servidor. ```ini [HTTP_REST] hostname=localhost port=9995 [HTTP_ROOT] Path=/api ``` -------------------------------- ### Estrutura mínima de configuração JSON Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/referencia-json Define a configuração básica necessária para iniciar o VdrCtrl, incluindo servidor, porta e pool de threads. ```tlpp Local jConfig := JsonObject():New() Local nResult := 0 jConfig['HTTPSERVER'] := JsonObject():New() jConfig['HTTPSERVER']['Enable'] := .T. jConfig['HTTPSERVER']['Servers'] := {"HTTP_REST"} jConfig['HTTP_REST'] := JsonObject():New() jConfig['HTTP_REST']['Port'] := 9995 jConfig['HTTP_REST']['HostName'] := "localhost" jConfig['HTTP_REST']['Locations'] := {"HTTP_ROOT"} jConfig['HTTP_ROOT'] := JsonObject():New() jConfig['HTTP_ROOT']['Path'] := "/" jConfig['HTTP_ROOT']['RootPath'] := "root/web" jConfig['HTTP_ROOT']['ThreadPool'] := "THREAD_POOL" jConfig['THREAD_POOL'] := JsonObject():New() jConfig['THREAD_POOL']['Environment'] := GetEnvServer() jConfig['THREAD_POOL']['MinThreads'] := 1 nResult := VdrCtrl():New():Start(jConfig) ``` -------------------------------- ### Configuração de Basic Auth via TlppData Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/referencia-ini Exemplo de configuração mínima para autenticação básica utilizando a chave TlppData no arquivo appserver.ini. ```ini [HTTPSERVER] Enable=1 Servers=HTTP_SRV ; ... outras chaves ... [HTTP_SRV] ; Injeta a configuração de segurança informando o esquema e a função validadora TlppData='{"Authorization":{"scheme":"basic","OnAuth":"U_onAuthorization"}}' ; ... outras chaves ... ``` -------------------------------- ### Inicialização de serviço com LoadURNs Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/sem-annotation Configuração inicial do servidor HTTP, incluindo definições de thread pool, content-types e a estrutura necessária para o mapeamento de URNs. ```tlpp #include "tlpp-core.th" Function u_fInitService() Local oVdrCtrl := VdrCtrl():New() as object Local cAppPath := "/examples" as character Local nResult := -1 as integer Local jConfig := JsonObject():New() as Json // Obtém o ambiente atual do servidor Local cEnv := GetEnvServer() as character // Definição das configurações do HttpServer jConfig['HTTPSERVER'] := JsonObject():New() jConfig['HTTPSERVER']['Enable'] := .T. jConfig['HTTPSERVER']['Log'] := .F. jConfig['HTTPSERVER']['Charset'] := "ISO-8859-1" jConfig['HTTPSERVER']['Servers'] := {"INIT_HTTP_REST"} jConfig['INIT_HTTP_REST'] := JsonObject():New() jConfig['INIT_HTTP_REST']['Port'] := 9995 jConfig['INIT_HTTP_REST']['HostName'] := "TLPP_REST_SERVER" jConfig['INIT_HTTP_REST']['Locations'] := {"HTTP_ROOT_01"} jConfig['INIT_HTTP_REST']['ContentTypes'] := "INIT_ContentTypes" jConfig['HTTP_ROOT_01'] := JsonObject():new() jConfig['HTTP_ROOT_01']['Path'] := cAppPath jConfig['HTTP_ROOT_01']['RootPath'] := "C:\tlppCore\bin\root\web" jConfig['HTTP_ROOT_01']['DefaultPage'] := {"index.html"} jConfig['HTTP_ROOT_01']['ThreadPool'] := "INIT_THREAD_POOL_01" jConfig['INIT_THREAD_POOL_01'] := JsonObject():new() jConfig['INIT_THREAD_POOL_01']['Environment'] := cEnv jConfig['INIT_THREAD_POOL_01']['MinThreads'] := 1 jConfig['INIT_THREAD_POOL_01']['MaxThreads'] := 4 jConfig['INIT_THREAD_POOL_01']['MinFreeThreads'] := 0 jConfig['INIT_THREAD_POOL_01']['GrowthFactor'] := 1 jConfig['INIT_THREAD_POOL_01']['AcceptTimeout'] := 10000 jConfig['INIT_THREAD_POOL_01']['InactiveTimeout'] := 30000 jConfig['INIT_THREAD_POOL_01']['ActiveTimeout'] := 120000 jConfig['INIT_THREAD_POOL_01']['Slaves'] := {"TP_AUX_1", "TP_AUX_2"} jConfig['TP_AUX_1'] := JsonObject():new() jConfig['TP_AUX_1']['Environment'] := cEnv jConfig['TP_AUX_1']['MinThreads'] := 2 jConfig['TP_AUX_1']['MaxThreads'] := 4 jConfig['TP_AUX_1']['MinFreeThreads'] := 0 jConfig['TP_AUX_1']['GrowthFactor'] := 1 jConfig['TP_AUX_1']['AcceptTimeout'] := 10000 jConfig['TP_AUX_1']['InactiveTimeout'] := 30000 jConfig['TP_AUX_1']['ActiveTimeout'] := 120000 jConfig['TP_AUX_2'] := JsonObject():new() jConfig['TP_AUX_2']['Environment'] := cEnv jConfig['TP_AUX_2']['MinThreads'] := 2 jConfig['TP_AUX_2']['MaxThreads'] := 4 jConfig['TP_AUX_2']['MinFreeThreads'] := 0 jConfig['TP_AUX_2']['GrowthFactor'] := 1 jConfig['TP_AUX_2']['AcceptTimeout'] := 10000 jConfig['TP_AUX_2']['InactiveTimeout'] := 30000 jConfig['TP_AUX_2']['ActiveTimeout'] := 120000 jConfig['INIT_ContentTypes'] := JsonObject():new() jConfig['INIT_ContentTypes']['htm'] := "text/html" jConfig['INIT_ContentTypes']['html'] := "text/html" jConfig['INIT_ContentTypes']['stm'] := "text/html" jConfig['INIT_ContentTypes']['tsp'] := "text/html" jConfig['INIT_ContentTypes']['js'] := "text/javascript" jConfig['INIT_ContentTypes']['json'] := "application/json;charset=utf-8" jConfig['INIT_ContentTypes']['*'] := "application/octet-stream" /* ----------------------------------------------------------- ``` -------------------------------- ### Registrando rotas dinâmicas com tlpp.doc.List() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/doc-generate/list-dinamico Utilize o método add para vincular um endpoint e método HTTP a uma função TLPP que retorna o JSON de documentação. ```tlpp oDoc := tlpp.doc.List():New() oDoc:add( "/init/dyn", "get", "U_FUNC_DYN_GET_DOC" ) oDoc:add( "/init/dyn", "put", "U_FUNC_DYN_PUT_DOC" ) oDoc:add( "/class/:param1", "get", "U_CLASS_DYN_GET_DOC" ) ``` -------------------------------- ### Client Parameter Provisioning with onAuthparams Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/authorization Provides client credentials and user authentication data. Returns a JsonObject containing configuration for the OAuth2 flow. ```tlpp user function paramsProvider() local oParams := JsonObject():New() oParams["client_id"] := "my_client" oParams["client_secret"] := "my_secret" oParams["username"] := "admin" oParams["password"] := "123456" oParams["grant_type"] := "password" oParams["access_expires"] := 3600 oParams["refresh_expires"] := "Date()+1" return oParams ``` ```tlpp user function flexibleParamsProvider() local oParams := JsonObject():New() oParams["client"] := {"id1", "id2"} oParams["users"] := {"user1", "user2"} oParams["passwords"] := {"pass1", "pass2"} oParams["grant_type"] := "password" oParams["access_expires"] := 3600 return oParams ``` -------------------------------- ### Verificar existência de cabeçalho na requisição com existKeyHeaderRequest Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Verifica se um cabeçalho específico existe na requisição. ```tlpp oRest:existKeyHeaderRequest( < cKey > ) ``` -------------------------------- ### Declarar parâmetros e respostas inline na annotation Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/metadados/rest-annotation Utilize esta sintaxe para documentação simples, declarando parâmetros e respostas diretamente na annotation sem a necessidade de uma função DOC. ```tlpp @Get(; endpoint="/rest/sample/doc/basic/02",; description="...",; title="DOC simples 02",; params='[{"name":"param1","in":"query",...}]',; responses='[{"statusCode":200,"description":"OK"},...]'; ) ``` -------------------------------- ### httpCallEnd() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/utilitarios Realiza o fechamento físico da resposta HTTP, despachando o buffer pendente e limpando recursos da thread. ```APIDOC ## httpCallEnd() ### Descrição Este método é responsável por realizar o fechamento físico da resposta HTTP no servidor REST. A sua execução realiza duas ações críticas em sequência: despacha o buffer de resposta pendente (runResponse) de volta ao cliente HTTP e efetua a limpeza e restauração de flags e recursos de controle do ciclo de vida da Thread ativa. ### Retorno - **Logical** - Indica se a rotina de envio e encerramento do ciclo HTTP foi concluída com sucesso. ``` -------------------------------- ### oRest:setKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Define um cabeçalho de resposta específico. ```APIDOC ## oRest:setKeyHeaderResponse( , ) ### Descrição Define um par chave-valor para o cabeçalho da resposta HTTP. ``` -------------------------------- ### Definição de Path Parameters Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/avisos-dicas O nome da variável de parâmetro deve ser consistente em todas as rotas que compartilham o mesmo caminho base. ```TLPP @Get("users/:id") // registra :id @Get("users/:userId") // ERRADO — nome diferente no mesmo path base ``` -------------------------------- ### Configure Basic Auth via INI Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/authorization Set the TlppData key within the server section of the INI file to enable Basic Auth. ```ini TlppData='{"Authorization":{"scheme":"basic","OnAuth":"U_onAuthorization"}}' ``` -------------------------------- ### Verificar fechamento após envio com getCloseAfterSend Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Verifica se a conexão deve ser fechada após o envio da resposta. ```tlpp oRest:getCloseAfterSend() ``` -------------------------------- ### oRest:updateKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Atualiza um cabeçalho de resposta existente. ```APIDOC ## oRest:updateKeyHeaderResponse( , ) ### Descrição Atualiza o valor de um cabeçalho de resposta previamente definido. ``` -------------------------------- ### Verificar existência de cabeçalho na resposta com existKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Verifica se um cabeçalho específico existe na resposta. ```tlpp oRest:existKeyHeaderResponse( < cKey > ) ``` -------------------------------- ### Configuração de ContentTypes Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/referencia-json Define o mapeamento de extensões de arquivo para tipos MIME e associa a configuração ao servidor REST. ```tlpp jConfig['MY_TYPES'] := JsonObject():New() jConfig['MY_TYPES']['json'] := "application/json" jConfig['MY_TYPES']['html'] := "text/html" jConfig['HTTP_REST']['ContentTypes'] := "MY_TYPES" ``` -------------------------------- ### Atualizar chave de cabeçalho com updateKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Atualiza o valor de uma chave existente no cabeçalho da resposta. ```tlpp oRest:updateKeyHeaderResponse( < cKey >, < cValue > ) ``` -------------------------------- ### Listagem de serviços registrados Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Endpoint para obter um JSON contendo todos os endpoints registrados no ambiente. ```http GET https://localhost:5012/rest/tlpp/rest/list/service ``` -------------------------------- ### Localizar mensagens de runtime com Localize() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/metadados/i18n Utilize a função Localize() no código fonte REST para traduzir mensagens de API em tempo de execução. ```tlpp cMsg := Localize(1, 'Parâmetro param1 recebido pela cadeia de consulta é inválido') ``` -------------------------------- ### Configuração do monitor de memória Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Configuração necessária no arquivo INI para habilitar o serviço de monitoramento de memória em uma porta dedicada. ```ini [APP_MONITOR] enable=1 ``` -------------------------------- ### Definir cabeçalhos de resposta com setHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Utilize este método para injetar múltiplos campos de cabeçalho simultaneamente na resposta HTTP. ```tlpp oRest:setHeaderResponse( < jValue > ) ``` -------------------------------- ### Generate Documentation with tlpp.doc.generate() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/doc-generate Function signature for exporting collected metadata to OpenAPI files. The first parameter must be the literal string 'swagger'. ```tlpp tlpp.doc.generate( , , [aPorts], [aLocales], [cListFunc] ) ``` -------------------------------- ### Consulta de versão do ambiente Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Endpoints para verificar a versão, build e patch do AppServer ou TLPP. ```http GET https://localhost:5012/rest/totvs/environment GET https://localhost:5012/rest/appserver/environment GET https://localhost:5012/rest/tlpp/environment ``` -------------------------------- ### oRest:appendKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Concatena um valor a um cabeçalho de resposta existente. ```APIDOC ## oRest:appendKeyHeaderResponse( , ) ### Descrição Adiciona ou concatena um valor a um cabeçalho de resposta existente. ``` -------------------------------- ### Estrutura básica de uma URL REST Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/primeiros-passos/composicao-url Representação visual dos componentes que formam uma URL de serviço REST. ```text https://host:porta/pathVirtual/endpoint?query=valor ``` -------------------------------- ### Enable Soft Mode for OnBlock Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-block Configure the AppServer to prevent restarts if an exception occurs during the OnBlock execution. ```ini [THREAD_POOL] TlppData={"OnBlockSoft":true} ``` -------------------------------- ### Definir corpo da resposta com setResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/escrita-resposta Utilize este método para injetar conteúdo no corpo da resposta. Chamadas sucessivas concatenam o texto ao invés de sobrescrevê-lo. ```tlpp oRest:setResponse( [ cMessage ] ) ``` -------------------------------- ### Configure OnStop in SLAVES_UEX Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-stop Define the OnStop entry point within the SLAVES_UEX configuration section. ```ini [SLAVES_UEX] OnStop=U_OnStop ``` -------------------------------- ### Definir chave de cabeçalho com setKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Define um par chave-valor específico no cabeçalho da resposta. ```tlpp oRest:setKeyHeaderResponse( < cKey >, < cValue > ) ``` -------------------------------- ### Referência de componente no JSON DOC Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/metadados/componentes Utilize o tipo component e o nome do componente definido para referenciá-lo em requestBody ou responses. ```json "type": "component", "component": "sampleBodyIn" ``` -------------------------------- ### Configure OnSelect in Thread Pool Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-select Configuration setting to define the OnSelect function within the Thread Pool section. ```ini [TP_UEX] OnSelect=U_OnSelect ``` -------------------------------- ### Concatenar chave de cabeçalho com appendKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Adiciona um valor a uma chave de cabeçalho existente, realizando a concatenação. ```tlpp oRest:appendKeyHeaderResponse( < cKey >, < cValue > ) ``` -------------------------------- ### Obter valor de cabeçalho específico com getKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Recupera o valor de um cabeçalho específico da resposta. ```tlpp oRest:getKeyHeaderResponse( < cKey >, @< cValue > ) ``` -------------------------------- ### Consulta de métricas de memória Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Exemplo de chamada para o endpoint de métricas de memória utilizando a porta do monitor. ```http GET https://localhost:32033/api/appserver/metrics?all ``` -------------------------------- ### Obter TlppData do Thread Pool Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/pool-servidor Retorna o objeto JSON com a chave TlppData configurada no thread pool. Não manipule o objeto diretamente, apenas leia suas propriedades. ```tlpp #include "tlpp-rest.th" user function exemplo_conceitual_getThreadPoolTlppData() local oRest := Tlpp.REST():new() local oTlppData := oRest:getThreadPoolTlppData() if (oTlppData != nil) // Apenas leitura das propriedades conout("TlppData: " + oTlppData:toJSON()) endif return ``` -------------------------------- ### Implement OnAllow logic Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-allow Use the oList object to explicitly allow or hide specific endpoints and HTTP methods. ```tlpp Function U_onAllow(oList) Local cEndpoint := '' Local cServiceName := oList:getServiceName() Local nServicePort := oList:getServicePort() Local cThreadPoolName := oList:getThreadPoolName() Local cUserData := oList:getUserData() Local jApis := oList:getApiList() cEndpoint := '/exemplo1/urn' oList:allow(cEndpoint, 'get') oList:allow(cEndpoint, 'post') oList:hide(cEndpoint, 'put') cEndpoint := '/exemplo2/urn' oList:allow(cEndpoint, 'get') Return Nil ``` -------------------------------- ### Configure OnSend in SLAVES_UEX Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-send Configuration entry to define the OnSend function within the SLAVES_UEX section. ```ini [SLAVES_UEX] OnSend=U_OnSend ``` -------------------------------- ### Remover chave de cabeçalho com deleteKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Remove uma chave específica do cabeçalho da resposta. Note que campos definidos pelo RFC podem quebrar a comunicação se removidos. ```tlpp oRest:deleteKeyHeaderResponse( < cKey > ) ``` -------------------------------- ### Estrutura da URL de operação Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/apis/referencia Formato padrão para compor a URL de acesso aos endpoints nativos do servidor REST. ```text {protocolo}://{host}:{porta}{Path da Location}{URI nativa} ``` ```text https://localhost:5012/rest/tlpp/rest/config │ │ │ └─ URI fixa do framework │ │ └─ prefixo da Location │ └─ porta do servidor HTTP_REST └─ host do servidor ``` -------------------------------- ### Obter código de retorno com getRetCodResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Retorna o código de retorno da resposta. ```tlpp oRest:getRetCodResponse() ``` -------------------------------- ### Montagem de JSON com JsonObject Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/metadados/json-documentacao Utilize JsonObject para construir a estrutura de resposta da função DOC, evitando a concatenação manual de strings. ```tlpp local jDoc := JsonObject():New() jDoc['title'] := "DOC simples 04" jDoc['params'] := { jParamQuery, jPathParam } return jDoc:toJson() ``` -------------------------------- ### Sintaxe de declaração de componente Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/metadados/componentes Define a estrutura básica para declarar uma propriedade de componente utilizando o arquivo de cabeçalho tlpp-doc.th. ```tlpp #include "tlpp-doc.th" TLPP COMPONENT ``` -------------------------------- ### Finalizar chamada HTTP com httpCallEnd Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/utilitarios Utilize este método para despachar o buffer de resposta e limpar recursos da thread ativa. ```tlpp exemplo_httpCallEnd.tlpp 11 linhas ``` -------------------------------- ### oRest:setHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Define o cabeçalho de resposta da requisição HTTP de forma estruturada, permitindo injetar múltiplos campos simultaneamente. ```APIDOC ## oRest:setHeaderResponse( ) ### Descrição Este método é responsável por definir o cabeçalho de resposta (Header Response) da requisição HTTP de forma estruturada. Ele permite injetar múltiplos campos de cabeçalho simultaneamente. ### Parâmetros - **jValue** (JsonObject) - Obrigatório - Objeto contendo as chaves e valores dos cabeçalhos. ### Retorno - **JsonObject** - Retorna um objeto JSON contendo todas as chaves e valores de cabeçalhos que foram definidos com sucesso. ``` -------------------------------- ### Obter corpo da resposta com getBodyResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Extrai o conteúdo do corpo da última resposta definida ou enviada, útil para validações ou logs em callbacks. ```tlpp oRest:getBodyResponse() ``` -------------------------------- ### Configure OnAllow in AppServer.ini Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-allow Define the OnAllow function within the Thread Pool section of the configuration file. ```ini [THREAD_POOL] UserExits=TP_UEX [TP_UEX] ;OnBlock=U_OnBlock OnAllow=U_OnAllow ``` -------------------------------- ### Configure OnBlock in Thread Pool Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-block Define the OnBlock function within the [THREAD_POOL] section of the configuration file. ```ini [THREAD_POOL] UserExits=TP_UEX [TP_UEX] OnBlock=U_onBlock ``` -------------------------------- ### Hierarquia de Configuração JSON Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/referencia-json Representação visual da estrutura de objetos JSON para configuração do servidor REST. ```text jConfig ├── HTTPSERVER → Enable, Servers[], Log, Charset ├── → Port, HostName, Locations[], LoadURNs, TlppData, … ├── → Path, RootPath, ThreadPool, CORS, … ├── → Environment, MinThreads, Slaves[], UserExits ├── → mesmo formato do thread pool ├── → OnStart, OnStop, OnSelect, OnError, OnBlock, OnSend ├── → extensão → MIME type └── → AllowOrigins[], AllowMethods[] ``` -------------------------------- ### Function-based Description Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/metadados/description Reference a compiled TLPP function within brackets to return dynamic JSON documentation. The function must be available in the same environment. ```text description="[U_rest_sample_04_basic_DOC]" ``` -------------------------------- ### tlpp.doc.generate() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/doc-generate Native function used to export collected documentation from metadata into YAML or JSON OpenAPI formats. ```APIDOC ## tlpp.doc.generate(cFormato, cNomeArquivo, [aPorts], [aLocales], [cListFunc]) ### Description Exports documentation collected from metadata to a YAML or JSON file. ### Parameters - **cFormato** (string) - Required - Format of the output: 'swagger' for YAML OpenAPI or 'json' for JSON. - **cNomeArquivo** (string) - Required - Prefix for the generated file (e.g., 'api_doc' results in 'api_doc_8080.yaml'). - **aPorts** (array) - Optional - List of ports to document (e.g., {8080}). If omitted, all ports are documented. - **aLocales** (array) - Optional - Languages for i18n texts (e.g., {'en-us', 'pt-br'}). - **cListFunc** (string) - Optional - Function name for dynamic routes (e.g., "U_ListDOCFunctions"). ``` -------------------------------- ### Direct Text Description Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/metadados/description Use direct text for simple, short endpoint explanations. The value is passed directly to the OpenAPI description field. ```text description="Exemplo de documentação simples, somente descrição" ``` -------------------------------- ### Extrair corpo da requisição com getBodyRequest Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-requisicao Retorna o conteúdo do corpo da requisição como texto bruto. O processamento do formato, como JSON ou XML, deve ser realizado pelo desenvolvedor. ```tlpp exemplo_getbodyrequest.tlpp ``` -------------------------------- ### Obter status da resposta com getStatusResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Retorna o código de status HTTP da resposta. ```tlpp oRest:getStatusResponse() ``` -------------------------------- ### Hierarquia de configuração Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/primeiros-passos/configuracao Representação visual da hierarquia de componentes do servidor REST. ```text HTTPSERVER → Server → Location → ThreadPool → Environment (RPO) ``` -------------------------------- ### oRest:getBodyResponse() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Retorna o conteúdo do corpo (Body) da última resposta definida ou enviada pelo servidor. ```APIDOC ## oRest:getBodyResponse() ### Descrição Este método extrai e retorna o conteúdo do corpo (Body) correspondente à última resposta definida ou enviada pelo servidor durante o ciclo de processamento da requisição atual. É ideal para validar, efetuar log ou interceptar a mensagem de resposta antes de ser devolvida ao cliente. ### Assinatura `oRest:getBodyResponse()` ### Retorno - **String**: O conteúdo de texto previamente injetado no objeto de resposta do servidor. ``` -------------------------------- ### Equivalência INI para JSON Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/referencia-json Exemplos de mapeamento entre as configurações do arquivo INI e a sintaxe de JsonObject no TLPP. ```tlpp jConfig['HTTPSERVER']['Enable'] := .T. ``` ```tlpp jConfig['HTTPSERVER']['Servers'] := {"HTTP_REST"} ``` ```tlpp jConfig['HTTP_REST']['Port'] := 9995 ``` ```tlpp jConfig['HTTP_REST']['Locations'] := {"HTTP_ROOT"} ``` ```tlpp jConfig['HTTP_ROOT']['Path'] := "/" ``` ```tlpp jConfig['HTTP_ROOT']['ThreadPool'] := "THREAD_POOL" ``` ```tlpp jConfig['THREAD_POOL']['Environment'] := "ENV" ``` ```tlpp jConfig['THREAD_POOL']['UserExits'] := "MY_UEX" ``` ```tlpp jConfig['MY_UEX']['OnStart'] := "fn" ``` -------------------------------- ### Marcar textos traduzíveis no JSON DOC Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/metadados/i18n Utilize o prefixo translate seguido pela função, ID e texto padrão dentro do JSON de documentação. ```json "title" : "translate:sample_complete_DOC:1:Exemplo completo",; ``` -------------------------------- ### oRest:resetResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/escrita-resposta Limpa o conteúdo da resposta e reseta o estado da mensagem. ```APIDOC ## oRest:resetResponse() ### Descrição Limpa o conteúdo acumulado na memória para iniciar uma nova mensagem de resposta do zero. ``` -------------------------------- ### Estrutura do nó LoadURNs Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/configuracoes/referencia-json Representação hierárquica da estrutura de rotas sem anotações no servidor. ```text LoadURNs └── "/caminho/:param" ← path completo da URN └── GET | POST | PUT | … ← verbo HTTP ├── ProgramType 0 = função, 1 = classe/método ├── ClassName ├── Function └── EndPoint array com segmentos da rota ``` -------------------------------- ### Define OnSelect Function Signature Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-select The required function signature for the OnSelect callback. ```advpl Function U_OnSelect(cClassName, cFunctionName, cProgramType) As Integer ``` -------------------------------- ### oRest:getBodyRequest() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-requisicao Extrai e retorna o conteúdo integral enviado no corpo (Body) da requisição HTTP como texto bruto. ```APIDOC ## oRest:getBodyRequest() ### Descrição Este método é responsável por extrair e retornar o conteúdo integral enviado no corpo (Body) da requisição HTTP efetuada pelo cliente. O conteúdo é retornado como texto bruto, cabendo ao desenvolvedor realizar o parse dos dados (JSON, XML, etc.). ### Assinatura `oRest:getBodyRequest()` ### Retorno - **String** - Conteúdo bruto do corpo da requisição. ``` -------------------------------- ### User Function onStop() Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-stop The OnStop function is a lifecycle hook that executes when a REST thread is destroyed. It takes no parameters and its return value is ignored by the framework. ```APIDOC ## User Function onStop() ### Description Executes when the REST thread is being destroyed. Use this for cleanup tasks like closing branches, releasing connections, or logging termination. ### Signature `User Function onStop() As Logical` ### Parameters None. ### Return Value - **Logical** - The return value is ignored by the framework. ### Important Notes - The thread may be terminating due to an error, so objects like `oRest` may already be destroyed. Always validate objects with `ValType()` before access. ### Example ```tlpp #include "tlpp-core.th" #include "tlpp-rest.th" User Function onStop() As Logical Local lOK := .T. As Logical lOK := U_fechaAmbiente() Return lOK ``` ``` -------------------------------- ### Obter cabeçalhos da resposta com getHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Retorna os cabeçalhos da resposta. ```tlpp oRest:getHeaderResponse() ``` -------------------------------- ### Definir ID de tradução na annotation REST Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/metadados/i18n Utilize o parâmetro description com um ID numérico entre colchetes para referenciar uma entrada de tradução. ```tlpp @Get(endpoint="/rest/sample/doc/basic/03", description="<1>") ``` -------------------------------- ### Define the OnAllow function signature Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-allow The function receives an oList object used to manage endpoint permissions. ```tlpp Function U_onAllow(oList) ``` -------------------------------- ### oRest:setResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/escrita-resposta Define o conteúdo (payload) do corpo da resposta HTTP. Chamadas sucessivas concatenam o conteúdo ao final da mensagem existente. ```APIDOC ## oRest:setResponse( [ cMessage ] ) ### Descrição Insere conteúdo no corpo da mensagem (Body Response) que será devolvida ao cliente. O conteúdo é concatenado caso o método seja chamado múltiplas vezes. ### Parâmetros - **cMessage** (Character) - Opcional - Conteúdo a ser adicionado ao corpo da resposta. ### Retorno - **Logical** - Retorna .T. se a injeção foi executada com êxito. ``` -------------------------------- ### oRest:deleteKeyHeaderResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/cabecalhos-resposta Remove um cabeçalho de resposta. ```APIDOC ## oRest:deleteKeyHeaderResponse( ) ### Descrição Remove um cabeçalho de resposta específico. Nota: Alguns campos definidos pelo RFC não podem ser removidos sem quebrar a comunicação. ``` -------------------------------- ### Obter mensagem de retorno com getRetMsgResponse Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/objeto-orest/leitura-resposta Retorna a mensagem associada ao código de retorno da resposta. ```tlpp oRest:getRetMsgResponse() ``` -------------------------------- ### OnSend Function Signature Source: https://totvs.github.io/totvstec-doc/docs/tlpp/rest/funcoes-usuario/on-send The standard signature for the U_OnSend function. ```tlpp Function U_OnSend() ```