ComposantsComponents › ESB › REST
Publie un service REST. Le job écoute une adresse HTTP ; à chaque requête reçue, il exécute le flux de la route qui correspond à son verbe et à son chemin. Les paramètres de la requête (chemin, adresse, en-têtes, formulaire, corps) arrivent dans les colonnes du flux, et un tRESTResponse renvoie la réponse. Un job n'en contient qu'un, et ne se termine pas tout seul : il sert les requêtes jusqu'à son arrêt.Publishes a REST service. The job listens on an HTTP address; for each request received, it runs the flow of the route that matches its verb and its path. The parameters of the request (path, query, headers, form, body) arrive in the columns of the flow, and a tRESTResponse sends the response back. A job holds only one, and does not end by itself: it serves requests until it is stopped.
EntréeInput
Aucune Pas de ligne en entrée. Il commence son sous-job ; il accepte un On Subjob Ok ou un On Subjob Error entrant.None No input row. It starts its subjob; it accepts one incoming On Subjob Ok or On Subjob Error.
SortieOutput
Un lien Main par ligne du Mapping de l'API REST, au nom de la route ; un lien Appel incorrect au plus. Pas de lien Iterate.One Main link per row of the REST API Mapping, named after the route; at most one Wrong Call link. No Iterate link.
Déclencheurs en sortieOutput triggers
On Subjob Ok On Subjob Error On Component Ok Run if
Le lien porte le nom de la route. La ligne qu'il transporte contient les paramètres de la requête ; la suite du flux prépare le document de la réponse (tXMLMap, tJavaRow, lecture d'une base…) et le tRESTResponse le renvoie.The link bears the name of the route. The row it carries holds the parameters of the request; the rest of the flow prepares the response document (tXMLMap, tJavaRow, a database read…) and the tRESTResponse sends it back.
Un seul tRESTRequest, autant de liens que de routes : à chaque requête, seul le flux de la route reconnue reçoit une ligne. Le lien Appel incorrect reçoit les requêtes qu'aucune route ne peut traiter.A single tRESTRequest, as many links as routes: for each request, only the flow of the matched route receives a row. The Wrong Call link receives the requests that no route can handle.
"/{id}"), ce que la route consomme et produit.Add one row to the REST API Mapping per route: the name of the output flow, the HTTP verb, the URI pattern ("/{id}"), what the route consumes and produces.tRESTResponse.Draw the link of each route (right-click › Row › the name of the route) to its processing, ended by a tRESTResponse.tRESTClient), puis arrêtez-le.Run the job: the console displays the address of the service, and the job waits for requests. Call it from a browser, an HTTP client or another job (tRESTClient), then stop it.Endpoint deployed at: … de la console est écrite par le Studio (et par Talaxie), pas par le job : un job lancé par son script ne l'affiche pas.The Endpoint deployed at: … line of the console is written by the Studio (and by Talaxie), not by the job: a job started from its script does not print it.Cannot start provider with uri: … Port N already in use.On a local address, the template first checks that the port is free; otherwise the service is not published and the error is Cannot start provider with uri: … Port N already in use.globalMap, remplie avec celle du job (connexions partagées comprises). Ce qu'un composant y range pendant une requête disparaît à la fin de celle-ci. Les variables de context, elles, sont communes à toutes les requêtes.Each request gets its own copy of globalMap, filled with the one of the job (shared connections included). What a component stores there during a request vanishes when it ends. The context variables, however, are common to all requests.tRESTResponse. Sans lui, le client reçoit un 404 au corps vide ; si un composant échoue, un 500 dont le corps est le message de l'exception (voir Pièges). Dans les deux cas le service continue.The response is the one set by the tRESTResponse. Without it, the client receives a 404 with an empty body; if a component fails, a 500 whose body is the message of the exception (see Pitfalls). In both cases the service keeps running.Les libellés sont ceux de l'onglet Composant ; le nom technique, en gris, est celui du paramètre dans le fichier du job.Labels are those of the Component tab; the technical name, in grey, is the parameter name in the job file.
| ParamètreSetting | DéfautDefault | VisibleShown | Description |
|---|---|---|---|
| DéfinitionDefinitionPROPERTY | — | Édition entrepriseEnterprise edition |
Groupe Définition de l'API : reprise d'une définition d'API du référentiel. La condition IS_STUDIO_EE_VERSION == 'true' le masque dans Talaxie.API Definition group: reuse of an API definition of the repository. The IS_STUDIO_EE_VERSION == 'true' condition hides it in Talaxie.
|
| Endpoint RESTREST EndpointREST_ENDPOINT | "http://localhost:8088/" |
ToujoursAlways |
Adresse du service, expression Java. Une adresse complète ("http://localhost:8088/clients") est prise telle quelle. Une adresse relative ("/clients") s'ajoute à l'URI par défaut des services REST des préférences ESB, http://127.0.0.1:8090/ à l'origine ; vide, c'est cette URI seule. Dans le Talend Runtime, la règle change : voir Dans le Talend Runtime.Address of the service, a Java expression. A full address ("http://localhost:8088/clients") is taken as is. A relative address ("/clients") is appended to the default URI of REST services of the ESB preferences, http://127.0.0.1:8090/ originally; empty, it is that URI alone. In the Talend Runtime the rule changes: see In the Talend Runtime.
|
| Mapping de l'API RESTREST API MappingSCHEMAS | videempty | ToujoursAlways | Les routes du service, une par ligne : voir Le mapping de l'API. Chaque ligne crée un schéma et un lien de sortie possibles.The routes of the service, one per row: see The API mapping. Each row creates a possible schema and output link. |
| Utiliser le Service LocatorUse Service LocatorSERVICE_LOCATOR | NonNo | ToujoursAlways |
Enregistre le service dans le Service Locator de Talend ESB, sous le nom {espace de noms}nom. Par défaut, n'a d'effet que dans le Talend Runtime.Registers the service in the Service Locator of Talend ESB, under the name {namespace}name. By default it only has an effect in the Talend Runtime.
|
| Espace de noms du serviceService NamespaceSERVICE_NAMESPACE | Préférence ESB (http://www.talend.org/rest/)ESB preference (http://www.talend.org/rest/) |
Service Locator cochéService Locator checked | Espace de noms du nom de service enregistré.Namespace of the registered service name. |
| Nom du serviceService NameSERVICE_NAME | "__NAME__" |
Service Locator cochéService Locator checked | En lecture seule.Read-only. |
| Utiliser Service Activity MonitorUse Service Activity MonitorSERVICE_ACTIVITY_MONITOR | NonNo | ToujoursAlways | Envoie les événements de chaque requête et de chaque réponse au Service Activity Monitor (SAM) de Talend ESB. Ajoute l'agent SAM aux bibliothèques du job.Sends the events of each request and each response to the Service Activity Monitor (SAM) of Talend ESB. Adds the SAM agent to the libraries of the job. |
| Utiliser l'authentification (Runtime ESB uniquement)Use Authentication (ESB runtime only)NEED_AUTH | NonNo | ToujoursAlways | Protège le service une fois déployé dans le Talend Runtime. Lancé depuis le Studio ou Talaxie, le service reste ouvert : le code du job ne contient aucun contrôle pour Basic HTTP ni pour Jeton SAML.Protects the service once deployed in the Talend Runtime. Started from the Studio or Talaxie, the service stays open: the code of the job holds no check for Basic HTTP nor for SAML Token. |
| (liste sans libellé)(list without a label)AUTH_TYPE | Basic HTTP | Authentification cochéeAuthentication checked |
Basic HTTP : utilisateurs du conteneur (domaine JAAS karaf). Jeton SAML : jeton dans l'en-tête de la requête. OpenID Connect n'est proposé que dans l'édition entreprise.Basic HTTP: users of the container (karaf JAAS realm). SAML Token: token in the header of the request. Open ID Connect is only offered in the enterprise edition.
|
| Utiliser autorisationUse AuthorizationNEED_AUTHORIZATION | NonNo | Édition entreprise, avec Jeton SAMLEnterprise edition, with SAML Token | Contrôle d'accès par rôle (XACML) dans le Runtime.Role-based access control (XACML) in the Runtime. |
| Utiliser la Corrélation MétierUse Business CorrelationUSE_BUSINESS_CORRELATION | NonNo | ToujoursAlways |
Lit ou crée un identifiant de corrélation (en-tête CorrelationID), disponible dans la variable CORRELATION_ID. Ajoute la bibliothèque correlationid-policy au job.Reads or creates a correlation identifier (CorrelationID header), available in the CORRELATION_ID variable. Adds the correlationid-policy library to the job.
|
| ParamètreSetting | DéfautDefault | VisibleShown | Description |
|---|---|---|---|
| Messages de logLog messagesLOG_MESSAGES | NonNo | ToujoursAlways |
Journalise chaque requête et chaque réponse (en-tête Authorization et éléments password masqués), au niveau INFO du journal du job. Lancé depuis Talaxie sans configuration de journal, le job n'en a rien affiché dans la console lors de nos essais.Logs each request and each response (Authorization header and password elements masked), at the INFO level of the job log. Started from Talaxie with no log configuration, the job displayed none of it in the console in our runs.
|
| Retour à la ligne auto. pour la requête JSONWrap JSON RequestWRAP_JSON_REQUEST | NonNo | ToujoursAlways |
Accepte un corps JSON sans clé racine : il est placé sous un élément <root>. Le libellé français est une traduction fautive de Wrap : il s'agit d'envelopper la requête. Voir Pièges.Accepts a JSON body without a root key: it is put under a <root> element. See Pitfalls.
|
| Attributs vers élémentsAttributes to ElementsATTRIBUTES_TO_ELEMENTS | OuiYes | ToujoursAlways |
Dans une réponse JSON, écrit un attribut XML comme une clé ordinaire : <client id="2"> donne "id":2. Décochée : "@id":2.In a JSON response, writes an XML attribute as a regular key: <client id="2"> gives "id":2. Unchecked: "@id":2.
|
| Convertir les valeurs JSON en chaînes de caractères dans la réponseConvert JSON values to String in responseCONVERT_JSON_VALUES_TO_STRING | NonNo | ToujoursAlways |
Écrit toutes les valeurs entre guillemets : "id":"2" au lieu de "id":2. Utile pour les valeurs qui ressemblent à des nombres sans en être (codes à zéros initiaux, très grands nombres).Writes every value between quotes: "id":"2" instead of "id":2. Useful for values that look like numbers without being ones (codes with leading zeros, very large numbers).
|
| Propriétés personnalisées du Service LocatorService Locator Custom PropertiesSERVICE_LOCATOR_CUSTOM_PROPERTIES | videempty | Service Locator cochéService Locator checked | Table nom / valeur, enregistrée avec le service dans le Service Locator.Name / value table, registered with the service in the Service Locator. |
| Propriétés personnalisées de l'activité de serviceService Activity Custom PropertiesSERVICE_ACTIVITY_MONITOR_CUSTOM_PROPERTIES | videempty | Service Activity Monitor cochéService Activity Monitor checked | Table nom / valeur, jointe aux événements envoyés au SAM.Name / value table, attached to the events sent to the SAM. |
Une ligne par route. Une requête est attribuée à la route dont le verbe, le modèle d'URI et les types conviennent.One row per route. A request is given to the route whose verb, URI pattern and types fit.
| ColonneColumn | DéfautDefault | Description |
|---|---|---|
| Flux de sortieOutput FlowSCHEMA | — | Nom de la route : celui de son schéma et de son lien de sortie. Une ligne sans lien tracé n'est pas publiée.Name of the route: the one of its schema and of its output link. A row with no link drawn is not published. |
| HTTP VerbHTTP_VERB | GET | GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. |
| Modèle d'URIURI PatternURI_PATTERN | "/" | Chemin de la route sous l'endpoint, entre guillemets. Une variable s'écrit entre accolades, avec une expression régulière au besoin : "/{id}", "/{id}/orders", "/{code:[A-Z]{2}[0-9]+}".Path of the route under the endpoint, between quotes. A variable is written between braces, with a regular expression if needed: "/{id}", "/{id}/orders", "/{code:[A-Z]{2}[0-9]+}". |
| ConsommeConsumesCONSUMES | <no-content> | Types de corps acceptés, pour POST, PUT et PATCH seulement (lecture seule pour les autres verbes) : XML ou JSON, XML (application/xml, text/xml), JSON (application/json), Form (application/x-www-form-urlencoded), Multipart (multipart/form-data, mixed, related), tous (*/*). Un autre Content-Type reçoit un 415.Accepted body types, for POST, PUT and PATCH only (read-only for the other verbs): XML or JSON, XML (application/xml, text/xml), JSON (application/json), Form (application/x-www-form-urlencoded), Multipart (multipart/form-data, mixed, related), any (*/*). Another Content-Type gets a 415. |
| ProduitProducesPRODUCES | XML ou JSONXML or JSON | Types de réponse possibles : XML ou JSON, XML, JSON, HTML (text/html), tous, <oneway>. Le type effectif est choisi d'après l'en-tête Accept de la requête ; sans lui, XML pour XML ou JSON. Un Accept que la route ne produit pas reçoit un 406.Possible response types: XML or JSON, XML, JSON, HTML (text/html), any, <oneway>. The actual type is chosen from the Accept header of the request; without it, XML for XML or JSON. An Accept that the route does not produce gets a 406. |
| FluxStreamingSTREAMING | NonNo | La réponse est écrite au fil des lignes qui arrivent au tRESTResponse, au lieu d'une seule ligne : voir sa page.The response is written as the rows reach the tRESTResponse, instead of a single row: see its page. |
Chaque route a son schéma, ouvert depuis la colonne Flux de sortie. Une colonne est un paramètre de la requête ; sa colonne Commentaire dit où le lire.Each route has its schema, opened from the Output Flow column. A column is a parameter of the request; its Comment column says where to read it.
| Commentaire de la colonneComment of the column | La colonne reçoitThe column receives | TypesTypes |
|---|---|---|
vide, ou pathempty, or path | La variable de même nom du modèle d'URI : id pour "/{id}". Une colonne dont le nom n'est pas dans le modèle reste nulle.The variable of the same name in the URI pattern: id for "/{id}". A column whose name is not in the pattern stays null. | String, Boolean, Byte, Short, Integer, Long, Float, Double, BigDecimal, List, Date |
query | Le paramètre de l'adresse : ?city=Paris.The query parameter: ?city=Paris. | les mêmesthe same |
header | L'en-tête HTTP de ce nom.The HTTP header of that name. | les mêmesthe same |
matrix | Le paramètre de matrice : /list;sort=name.The matrix parameter: /list;sort=name. | les mêmesthe same |
form | Le champ du formulaire, pour une route qui consomme Form.The form field, for a route that consumes Form. | les mêmesthe same |
multipart | La partie de ce nom, pour une route qui consomme Multipart. Les en-têtes et le nom de fichier de chaque partie sont dans les variables ATTACHMENT_HEADERS et ATTACHMENT_FILENAMES.The part of that name, for a route that consumes Multipart. The headers and the file name of each part are in the ATTACHMENT_HEADERS and ATTACHMENT_FILENAMES variables. | les mêmes sauf List, plus byte[] et Documentthe same except List, plus byte[] and Document |
vide, colonne nommée bodyempty, column named body | Le corps de la requête (POST, PUT, PATCH ; pas avec Form ni Multipart). En Document, un corps JSON est converti en XML.The body of the request (POST, PUT, PATCH; not with Form nor Multipart). As a Document, a JSON body is converted to XML. | Document, String, byte[] |
header(User-Agent).The parameter bears the name of the column. If it cannot be a column name, give it between parentheses in the comment: header(User-Agent)."yyyy-MM-dd") ; une valeur qui ne le respecte pas reçoit un 400.A Date is read with the date pattern of the column ("yyyy-MM-dd"); a value that does not follow it gets a 400.abc pour un Integer) reçoit un 404.A value that cannot be converted to the type of the column (abc for an Integer) gets a 404.
Fixe, quatre colonnes : uri (String, le chemin sous l'endpoint), method (String, le verbe), status (Integer, le code HTTP renvoyé) et error (String, le message).Fixed, four columns: uri (String, the path under the endpoint), method (String, the verb), status (Integer, the HTTP code returned) and error (String, the message).
Le flux ne sert pas qu'à journaliser : terminé par un tRESTResponse, il remplace la réponse d'erreur par la sienne (voir l'exemple Une réponse d'erreur construite par le job).The flow is not only for logging: ended by a tRESTResponse, it replaces the error response with its own (see the An error response built by the job example).
Requêtes et réponses copiées d'une exécution du job en local : > ce que le client envoie, < l'état et les en-têtes de la réponse, puis son corps. Les en-têtes Server et Date sont retirés, les autres aussi quand ils n'apportent rien.Requests and responses copied from a local run of the job: > what the client sends, < the status and the headers of the response, then its body. The Server and Date headers are removed, and so are the others when they add nothing.
Un job dont le tRESTRequest a pour Endpoint REST "http://localhost:8088/clients" et ces routes :A job whose tRESTRequest has "http://localhost:8088/clients" as REST Endpoint and these routes:
| Flux de sortieOutput Flow | HTTP Verb | Modèle d'URIURI Pattern | ConsommeConsumes | ProduitProduces | Schéma (commentaire)Schema (comment) |
|---|---|---|---|---|---|
| getClient | GET | "/{id}" | — | XML ou JSONXML or JSON | id Integer |
| listClients | GET | "/" | — | XML ou JSONXML or JSON | city String (query), limit Integer (query, défaut 10), agent String (header(User-Agent))city String (query), limit Integer (query, default 10), agent String (header(User-Agent)) |
| addClient | POST | "/" | XML ou JSONXML or JSON | XML ou JSONXML or JSON | body Document |
| countClients | GET | "/count" | — | JSON | — |
Chaque route va vers un tJavaRow qui construit le document de la réponse à partir de trois clients en dur, puis vers un tRESTResponse. Un lien Appel incorrect va vers un tLogRow. Le tJavaRow de listClients et celui d'addClient affichent ce qu'ils reçoivent. Au lancement, la console affiche :Each route goes to a tJavaRow that builds the response document from three hard-coded clients, then to a tRESTResponse. A Wrong Call link goes to a tLogRow. The tJavaRow of listClients and the one of addClient print what they receive. At start, the console displays:
Endpoint deployed at: http://localhost:8088/clients
La colonne id reçoit 2. Le même document, renvoyé par le tRESTResponse, sort en XML ou en JSON selon l'en-tête Accept :The id column receives 2. The same document, sent back by the tRESTResponse, comes out as XML or JSON depending on the Accept header:
> GET http://localhost:8088/clients/2
> Accept: application/xml
< HTTP 200 OK
< content-type: application/xml
< transfer-encoding: chunked
<?xml version="1.0" encoding="UTF-8"?>
<client id="2"><name>Grace Petit</name><city>Lyon</city></client>
> GET http://localhost:8088/clients/2
> Accept: application/json
< HTTP 200 OK
< content-type: application/json
< transfer-encoding: chunked
{"client":{"id":2,"name":"Grace Petit","city":"Lyon"}}
Sans en-tête Accept, la réponse est en XML.Without an Accept header, the response is XML.
Trois appels à listClients ; sous chacun, la ligne qu'affiche son tJavaRow dans la console du service (ureq/2.12.1 est le client HTTP de l'essai) :Three calls to listClients; under each one, the line its tJavaRow prints in the console of the service (ureq/2.12.1 is the HTTP client of the test):
> GET http://localhost:8088/clients listClients: city=null, limit=10, agent=ureq/2.12.1 > GET http://localhost:8088/clients?city=Paris listClients: city=Paris, limit=10, agent=ureq/2.12.1 > GET http://localhost:8088/clients?limit=1 > User-Agent: doc-test/1.0 listClients: city=null, limit=1, agent=doc-test/1.0
Réponse du dernier appel :Response of the last call:
< HTTP 200 OK < content-type: application/xml < transfer-encoding: chunked <?xml version="1.0" encoding="UTF-8"?> <clients><client><id>1</id><name>Ada Martin</name><city>Paris</city></client></clients>
addClient consomme XML ou JSON et reçoit le corps dans une colonne body de type Document. Le tJavaRow affiche ce document : il est le même pour les deux appels.addClient consumes XML or JSON and receives the body in a body column of type Document. The tJavaRow prints that document: it is the same for both calls.
> POST http://localhost:8088/clients
> Content-Type: application/xml
> Accept: application/xml
>
> <client><name>Marie Blanc</name><city>Nantes</city></client>
< HTTP 201 Created
< location: http://localhost:8088/clients/4
< content-type: application/xml
< transfer-encoding: chunked
<?xml version="1.0" encoding="UTF-8"?>
<client><id>4</id><name>Marie Blanc</name><city>Nantes</city></client>
> POST http://localhost:8088/clients
> Content-Type: application/json
> Accept: application/json
>
> {"client":{"name":"Marie Blanc","city":"Nantes"}}
< HTTP 201 Created
< location: http://localhost:8088/clients/4
< content-type: application/json
< transfer-encoding: chunked
{"client":{"id":4,"name":"Marie Blanc","city":"Nantes"}}Console du service, pour chacun des deux appels :Console of the service, for each of the two calls:
addClient: <?xml version="1.0" encoding="UTF-8"?> <client><name>Marie Blanc</name><city>Nantes</city></client>
Le code 201 et l'en-tête Location viennent du tRESTResponse.The 201 code and the Location header come from the tRESTResponse.
Des requêtes que le service ne peut pas traiter, avec entre parenthèses ce qui les rend incorrectes. Pour chacune, la réponse reçue par le client puis, précédée de →, la ligne du tLogRow relié à Appel incorrect (uri|method|status|error) :Requests that the service cannot handle, with between parentheses what makes them wrong. For each one, the response received by the client then, preceded by →, the row of the tLogRow connected to Wrong Call (uri|method|status|error):
> GET http://localhost:8088/clients/abc (id n'est pas un entier / id is not an integer)
< HTTP 404 Not Found
< content-type: application/xml
< content-length: 23
For input string: "abc"
→ abc|GET|404|For input string: "abc"
> GET http://localhost:8088/clients/2/orders (aucune route / no route)
< HTTP 404 Not Found
HTTP 404 Not Found
→ 2/orders|GET|404|HTTP 404 Not Found
> DELETE http://localhost:8088/clients/2 (verbe sans route / verb without a route)
< HTTP 405 Method Not Allowed
HTTP 405 Method Not Allowed
→ 2|DELETE|405|HTTP 405 Method Not Allowed
> POST http://localhost:8088/clients (Content-Type: text/plain)
< HTTP 415 Unsupported Media Type
HTTP 415 Unsupported Media Type
→ /|POST|415|HTTP 415 Unsupported Media Type
> POST http://localhost:8088/clients (corps / body: <client><name>Marie)
< HTTP 400 Bad Request
Unexpected EOF; was expecting a close tag for element <name>
at [row,col {unknown-source}]: [1,19]
→ /|POST|400|Unexpected EOF; was expecting a close tag for element <name>
at [row,col {unknown-source}]: [1,19]
> GET http://localhost:8088/clients/2 (Accept: text/csv)
< HTTP 406 Not Acceptable
HTTP 406 Not Acceptable
→ 2|GET|406|HTTP 406 Not Acceptable
> GET http://localhost:8088/clients?limit=many
< HTTP 404 Not Found
For input string: "many"
→ /|GET|404|For input string: "many"
Le corps de ces réponses est le texte brut du message, même quand l'en-tête annonce application/xml ou application/json : le type est celui que le client a demandé. Une requête hors de l'endpoint (http://localhost:8088/) n'atteint pas le job : le serveur répond 404, sans ligne Appel incorrect.The body of these responses is the raw text of the message, even when the header announces application/xml or application/json: the type is the one the client asked for. A request outside the endpoint (http://localhost:8088/) does not reach the job: the server answers 404, with no Wrong Call row.
Le tJavaRow range le code dans globalMap et écrit un corps JSON dans une colonne body de type String ; le tRESTResponse a pour code de statut l'expression ((Integer) globalMap.get("status")).The tJavaRow stores the code in globalMap and writes a JSON body to a body column of type String; the tRESTResponse has the ((Integer) globalMap.get("status")) expression as its status code.
globalMap.put("status", input_row.status);
output_row.body = "{\"status\":" + input_row.status + ",\"path\":\"" + input_row.uri + "\",\"message\":\""
+ input_row.error.replace("\"", "'").replace("\n", " ") + "\"}";
> GET http://localhost:8088/clients/nothing
> Accept: application/json
< HTTP 404 Not Found
< content-type: application/json
< content-length: 62
{"status":404,"path":"nothing","message":"HTTP 404 Not Found"}
Le type de la réponse reste celui que le client demande : la même erreur, appelée avec Accept: application/xml, a renvoyé ce corps JSON sous l'en-tête content-type: application/xml.The type of the response remains the one the client asks for: the same error, called with Accept: application/xml, returned this JSON body under the content-type: application/xml header.
Une route GET "/search" dont le schéma a q (String, query, non nullable) et since (Date, query, modèle "yyyy-MM-dd"), et une route POST "/login" qui consomme Form, avec user (String, form) et remember (Boolean, form). Chaque flux renvoie ses colonnes en texte. Les erreurs passent par le flux de l'exemple précédent.A GET "/search" route whose schema has q (String, query, not nullable) and since (Date, query, "yyyy-MM-dd" pattern), and a POST "/login" route that consumes Form, with user (String, form) and remember (Boolean, form). Each flow returns its columns as text. The errors go through the flow of the previous example.
> GET http://localhost:8088/clients/search?q=martin&since=2026-01-15
< HTTP 200 OK
q=martin, since=Thu Jan 15 00:00:00 CET 2026
> GET http://localhost:8088/clients/search
< HTTP 400 Bad Request
{"status":400,"path":"search","message":"400 Bad Request [q] in tRESTRequest_1:search is required!"}
> GET http://localhost:8088/clients/search?q=martin&since=15/01/2026
< HTTP 400 Bad Request
{"status":400,"path":"search","message":"[since_tRESTRequest_1] Date parameter has invalid format!"}
> POST http://localhost:8088/clients/login
> Content-Type: application/x-www-form-urlencoded
>
> user=ada&remember=true
< HTTP 200 OK
user=ada, remember=true
Toutes sont remplies à chaque requête, dans la copie de globalMap de cette requête, et se lisent dans le flux de la route. Valeurs relevées dans un flux pour l'appel GET http://localhost:8088/clients/info/A7?detail=full (endpoint "http://localhost:8088/clients", route "/info/{code}") :All are filled for each request, in the copy of globalMap of that request, and are read in the flow of the route. Values read in a flow for the GET http://localhost:8088/clients/info/A7?detail=full call (endpoint "http://localhost:8088/clients", route "/info/{code}"):
| VariableVariable | Type | Valeur relevéeValue read | Description |
|---|---|---|---|
URI | String | info/A7 | Chemin sous l'endpoint, sans barre initiale.Path under the endpoint, with no leading slash. |
URI_BASE | String | http://localhost:8088/clients | Adresse de l'endpoint.Address of the endpoint. |
URI_ABSOLUTE | String | http://localhost:8088/clients/info/A7 | Adresse appelée, sans ses paramètres.Called address, without its parameters. |
URI_REQUEST | String | http://localhost:8088/clients/info/A7?detail=full | Adresse appelée, entière.Called address, in full. |
HTTP_METHOD | String | GET | Verbe de la requête.Verb of the request. |
PRINCIPAL_NAME | String | null | Utilisateur authentifié ; nul sans authentification, donc toujours hors du Runtime.Authenticated user; null without authentication, so always outside the Runtime. |
CORRELATION_ID | String | null | Identifiant de corrélation, avec Utiliser la Corrélation Métier.Correlation identifier, with Use Business Correlation. |
ATTACHMENT_HEADERS | Map<String, Map<String, List<String>>> | null | En-têtes de chaque partie d'une requête Multipart, par nom de partie.Headers of each part of a Multipart request, by part name. |
ATTACHMENT_FILENAMES | Map<String, String> | null | Nom de fichier de chaque partie.File name of each part. |
NB_LINE | Integer | null | Posée à la fin du traitement de la requête, toujours à 1, dans la copie de globalMap de la requête : ce n'est pas le nombre de requêtes servies.Set at the end of the processing of the request, always to 1, in the copy of globalMap of the request: it is not the number of requests served. |
((String) globalMap.get("tRESTRequest_1_URI"))
((String) globalMap.get("tRESTRequest_1_HTTP_METHOD"))
Lu dans les modèles du composant et dans le modèle de déploiement de Talaxie (job-rest-template.xml), sans essai dans un conteneur.Read in the templates of the component and in the deployment template of Talaxie (job-rest-template.xml), with no run in a container.
| Studio, Talaxie, script du jobStudio, Talaxie, job script | Talend Runtime (Karaf)Talend Runtime (Karaf) | |
|---|---|---|
| Serveur HTTPHTTP server | Le job démarre le sien (Jetty), sur le port de l'endpoint, et l'arrête avec lui.The job starts its own (Jetty), on the port of the endpoint, and stops it with itself. | Le job est un bundle OSGi : le service est déclaré au conteneur (jaxrs:server), le job ne démarre pas de serveur.The job is an OSGi bundle: the service is declared to the container (jaxrs:server), the job starts no server. |
Endpoint relatif ("/clients")Relative endpoint ("/clients") | Ajouté à l'URI par défaut des préférences : http://127.0.0.1:8090/clients.Appended to the default URI of the preferences: http://127.0.0.1:8090/clients. | Publié sous le contexte /services du conteneur : http://hôte:8040/services/clients avec le port d'origine du Runtime. Un /services/ écrit en tête de l'endpoint est retiré ; un endpoint vide devient / suivi du nom du job.Published under the /services context of the container: http://host:8040/services/clients with the original port of the Runtime. A leading /services/ written in the endpoint is removed; an empty endpoint becomes / followed by the name of the job. |
Endpoint complet ("http://…")Full endpoint ("http://…") | Pris tel quel.Taken as is. | Repris tel quel dans la déclaration du service. Pour un service à déployer, préférez un endpoint relatif.Copied as is into the declaration of the service. For a service meant to be deployed, prefer a relative endpoint. |
Endpoint avec context.Endpoint with context. | Expression Java évaluée par le job.Java expression evaluated by the job. | Évalué au déploiement à partir des valeurs du contexte du job, que la configuration du conteneur peut remplacer.Evaluated at deployment from the context values of the job, which the configuration of the container can override. |
| AuthentificationAuthentication | Aucune : le service est ouvert.None: the service is open. | Basic HTTP : filtre JAAS sur le domaine karaf. Jeton SAML : jeton vérifié avec les réglages de signature du conteneur (org.talend.esb.job.service).Basic HTTP: JAAS filter on the karaf realm. SAML Token: token checked with the signature settings of the container (org.talend.esb.job.service). |
| Service LocatorService Locator | Ignoré par défaut ; une préférence ESB permet de l'utiliser, avec un Service Locator joignable.Ignored by default; an ESB preference allows using it, with a reachable Service Locator. | Service enregistré par la fonction du conteneur.Service registered by the feature of the container. |
| Service Activity MonitorService Activity Monitor | Agent embarqué dans le job, configuré par ses fichiers META-INF/tesb.Agent embedded in the job, configured by its META-INF/tesb files. | Agent du conteneur.Agent of the container. |
Une route dont le tJavaRow lève new RuntimeException("Database unavailable"). Le client reçoit le message de l'exception comme corps :A route whose tJavaRow throws new RuntimeException("Database unavailable"). The client receives the message of the exception as the body:
> GET http://localhost:8088/clients/fail > Accept: application/xml < HTTP 500 Server Error < content-type: application/xml < content-length: 20 Database unavailable
Console du service (nom du job remplacé par MyService, pile abrégée) :Console of the service (job name replaced with MyService, shortened stack):
Exception in component tJavaRow_5 (MyService) java.lang.RuntimeException: Database unavailable at demo.myservice_0_1.MyService.tRESTRequest_1_LoopProcess(MyService.java:5987) at demo.myservice_0_1.MyService$RestServiceProviderImpl4TalendJob.processRequest(MyService.java:557) at demo.myservice_0_1.MyService$RestServiceProviderImpl4TalendJob.failing(MyService.java:734) …
Le service continue de répondre. Mais le message d'une exception peut en dire trop (nom d'une table, d'un serveur) : interceptez les erreurs prévisibles dans le flux et répondez par un tRESTResponse au code voulu.The service keeps answering. But the message of an exception may say too much (the name of a table, of a server): catch the foreseeable errors in the flow and answer with a tRESTResponse with the wanted code.
Le corps JSON est converti en XML, qui n'a qu'une racine. Envoyé à la route addClient de l'exemple, {"name":"Marie Blanc","city":"Nantes"} donne ce document : la seconde clé est perdue, sans erreur.The JSON body is converted to XML, which has only one root. Sent to the addClient route of the example, {"name":"Marie Blanc","city":"Nantes"} gives this document: the second key is lost, with no error.
addClient: <?xml version="1.0" encoding="UTF-8"?> <name>Marie Blanc</name>
Avec Wrap JSON Request cochée, le même corps arrive entier, sous <root>. Un corps qui a déjà sa clé racine y est placé lui aussi :With Wrap JSON Request checked, the same body arrives whole, under <root>. A body that already has its root key is put there too:
addClient: <?xml version="1.0" encoding="UTF-8"?> <root><name>Marie Blanc</name><city>Nantes</city></root> addClient: <?xml version="1.0" encoding="UTF-8"?> <root><client><name>Marie Blanc</name><city>Nantes</city></client></root>
Une route GET "/ping" reliée à un tJavaRow qui affiche ping, sans tRESTResponse. Le flux s'exécute (la console du service affiche ping), mais le client reçoit :A GET "/ping" route connected to a tJavaRow that prints ping, with no tRESTResponse. The flow runs (the console of the service displays ping), but the client receives:
> GET http://localhost:8088/clients/ping < HTTP 404 Not Found < content-length: 0
Il en va de même pour une branche du flux qui ne mène à aucun tRESTResponse (une sortie de filtre oubliée, une ligne rejetée).The same goes for a branch of the flow that leads to no tRESTResponse (a forgotten filter output, a rejected row).
Deux routes produisant <oneway> (un POST avec un corps, un GET), reliées à un tJavaRow qui affiche une ligne : le client a reçu 202 Accepted aussitôt, mais la console du service n'a rien affiché, ni la ligne ni une erreur, même après plusieurs secondes. Tant que ce point n'est pas éclairci, répondez plutôt par un tRESTResponse et traitez ensuite.Two routes producing <oneway> (a POST with a body, a GET), connected to a tJavaRow that prints a line: the client received 202 Accepted at once, but the console of the service displayed nothing, neither the line nor an error, even after several seconds. Until this point is cleared up, rather answer with a tRESTResponse and process afterwards.
"/count" (qui produit JSON) et "/{id}" acceptent tous deux /clients/count. Appelé avec Accept: application/xml, que la première ne produit pas, c'est la seconde qui est choisie : le service a répondu 404 For input string: "count" au lieu de 406. Donnez les mêmes types aux routes qui se recouvrent, ou restreignez la variable : "/{id:[0-9]+}"."/count" (which produces JSON) and "/{id}" both accept /clients/count. Called with Accept: application/xml, which the first one does not produce, the second one is chosen: the service answered 404 For input string: "count" instead of 406. Give the same types to routes that overlap, or restrict the variable: "/{id:[0-9]+}".
En JSON, une liste d'un seul élément sort comme un objet : {"clients":{"client":{…}}} pour un client, {"clients":{"client":[…]}} pour deux. Le réglage Clés de tableaux JSON du tRESTResponse corrige cela.In JSON, a list of a single element comes out as an object: {"clients":{"client":{…}}} for one client, {"clients":{"client":[…]}} for two. The JSON Array Keys setting of the tRESTResponse fixes this.
Utiliser l'authentification n'agit que dans le Talend Runtime. Un job lancé depuis le Studio, Talaxie ou son script répond à tout le monde : ne l'exposez pas sur une adresse joignable depuis l'extérieur en comptant sur cette case.Use Authentication only acts in the Talend Runtime. A job started from the Studio, Talaxie or its script answers everyone: do not expose it on an address reachable from outside while relying on this box.
Deux requêtes simultanées parcourent le même job en même temps. Ne rangez rien dans context pendant une requête : l'autre le verrait. Utilisez globalMap, propre à chaque requête. Une connexion à une base ouverte avant le tRESTRequest est partagée par toutes les requêtes.Two simultaneous requests go through the same job at the same time. Store nothing in context during a request: the other one would see it. Use globalMap, private to each request. A database connection opened before the tRESTRequest is shared by all requests.
Un job à tRESTRequest ne se termine que par son arrêt. Un tPostjob, un On Subjob Ok en fin de job ou un job parent qui attend la fin (tRunJob) ne conviennent donc pas.A job with a tRESTRequest only ends by being stopped. A tPostjob, an On Subjob Ok at the end of the job or a parent job that waits for the end (tRunJob) are therefore not suitable.
tRESTResponse · renvoyer la réponse d'une routesend back the response of a routetRESTClient · appeler un service REST depuis un jobcall a REST service from a jobtESBProviderRequest · publier une opération de service SOAPpublish an operation of a SOAP servicetJavaRow · construire le document de la réponse en Javabuild the response document in JavatLogRow · afficher les appels incorrectsdisplay the wrong callstRouteInput · recevoir le message d'une routereceive the message of a route