ComposantsComponents › ESB › REST
Renvoie la réponse HTTP de la requête que le tRESTRequest du job vient de recevoir : le corps, pris dans la colonne body de la ligne qu'il reçoit, le code de statut et les en-têtes. Il termine le flux d'une route ; chaque route qui doit répondre a le sien.Sends back the HTTP response of the request that the tRESTRequest of the job has just received: the body, taken from the body column of the row it receives, the status code and the headers. It ends the flow of a route; each route that must answer has its own.
EntréeInput
Un lien Main, obligatoire : une ligne par réponse, avec une colonne body.One Main link, required: one row per response, with a body column.
SortieOutput
Aucune Il termine le flux.None It ends the flow.
Déclencheurs en sortieOutput triggers
On Component Ok Run if
Le composant placé juste avant produit une ligne dont la colonne body contient la réponse : un Document construit par un tXMLMap, une chaîne ou des octets préparés par un tJavaRow.The component placed just before produces a row whose body column holds the response: a Document built by a tXMLMap, a string or bytes prepared by a tJavaRow.
Deux sorties, deux tRESTResponse : le premier répond OK (200), le second Ressource introuvable (404). Pour une requête, une seule des deux sorties doit produire une ligne.Two outputs, two tRESTResponse components: the first one answers OK (200), the second one Resource Not Found (404). For one request, only one of the two outputs must produce a row.
body, prend ce type.Choose the body type: Document, string or bytes. The schema of the component, a single body column, takes that type.body du même type.Connect the component that prepares the response to it: its output must have a body column of the same type.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 |
|---|---|---|---|
| Retourner le type de corpsReturn Body TypeRESPONSE_TYPE | Document | ToujoursAlways |
Type de la colonne body du schéma : Document, Chaîne de caractères ou Byte[]. Un Document est écrit en XML ou converti en JSON, selon le type que la requête accepte ; une chaîne ou des octets sont envoyés tels quels.Type of the body column of the schema: Document, String or Byte[]. A Document is written as XML or converted to JSON, depending on the type the request accepts; a string or bytes are sent as they are.
|
| Retourner le code de statutReturn status codeSTATUS_CODE | OK (200) | ToujoursAlways | OK (200), Mauvaise requête (400), Ressource introuvable (404), Erreur interne au serveur (500) ou << custom >>.OK (200), Bad Request (400), Resource Not Found (404), Internal Server Error (500) or << custom >>. |
| (champ sans libellé)(field without a label)CUSTOM_STATUS_CODE | 200 |
Code << custom >><< custom >> code |
Le code, expression Java de type Integer : 201, 204, ou une valeur calculée dans le flux, ((Integer) globalMap.get("status")).The code, a Java expression of type Integer: 201, 204, or a value computed in the flow, ((Integer) globalMap.get("status")).
|
| SchémaSchemaSCHEMA | body (Document)body (Document) |
ToujoursAlways |
Une seule colonne, body, dont seul le type change. C'est la colonne body du lien entrant qui est lue : une ligne qui n'en a pas donne une réponse au corps vide.A single column, body, of which only the type changes. The body column of the incoming link is the one read: a row that has none gives a response with an empty body.
|
| ParamètreSetting | DéfautDefault | VisibleShown | Description |
|---|---|---|---|
| En-têtes de réponseResponse HeadersRESPONSE_HEADERS | videempty | ToujoursAlways |
Table nom / valeur, deux expressions Java : "Location", "http://localhost:8088/clients/4". Un en-tête Content-Type remplace le type choisi par le service. Les lignes Set-Cookie sont réunies, et chaque nom=valeur devient un cookie.name / value table, two Java expressions: "Location", "http://localhost:8088/clients/4". A Content-Type header replaces the type chosen by the service. The Set-Cookie rows are merged, and each name=value becomes a cookie.
|
| Retirer la racine de la réponse JSONDrop JSON Response RootUNWRAP_JSON_RESPONSE | NonNo | ToujoursAlways |
En JSON, retire la clé qui correspond à l'élément racine du Document : {"id":2,…} au lieu de {"client":{"id":2,…}}. Sans effet sur une réponse XML.In JSON, removes the key that matches the root element of the Document: {"id":2,…} instead of {"client":{"id":2,…}}. No effect on an XML response.
|
| Clés de tableaux JSONJSON Array KeysJSON_ARRAY_KEYS | videempty | ToujoursAlways |
Expression Java : les noms des éléments à écrire toujours comme des tableaux JSON, séparés par des espaces ("client order"). Sans elle, un élément qui n'apparaît qu'une fois sort comme un objet.Java expression: the names of the elements to always write as JSON arrays, separated by spaces ("client order"). Without it, an element that appears only once comes out as an object.
|
Rest response already sent. : le client reçoit la première réponse.A second row, on the same tRESTResponse or on another one, fails with Rest response already sent.: the client receives the first response.tRESTRequest : celui de la colonne Produit de la route que l'en-tête Accept de la requête retient.The content type is decided by the tRESTRequest: the one of the Produces column of the route that the Accept header of the request selects.tRESTRequest, chaque ligne reçue est écrite aussitôt dans la réponse : le tRESTResponse accepte alors autant de lignes que le flux en produit.When the Streaming box of the route is checked in the tRESTRequest, each row received is written at once to the response: the tRESTResponse then accepts as many rows as the flow produces.<wrapper> en XML, dans un tableau […] en JSON.The documents are gathered under a <wrapper> element in XML, in a […] array in JSON.
Requêtes et réponses copiées d'une exécution en local d'un job dont le tRESTRequest a pour endpoint "http://localhost:8088/clients" : > ce que le client envoie, < l'état et les en-têtes de la réponse (sans Server ni Date), puis son corps.Requests and responses copied from a local run of a job whose tRESTRequest has "http://localhost:8088/clients" as its endpoint: > what the client sends, < the status and the headers of the response (without Server nor Date), then its body.
La route produit XML ou JSON. Le tJavaRow range dans body le document <client id="2">… ; le tRESTResponse garde ses réglages par défaut.The route produces XML or JSON. The tJavaRow stores the <client id="2">… document in body; the tRESTResponse keeps its default settings.
> 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"}}
En JSON, l'attribut id devient une clé et les valeurs numériques perdent leurs guillemets : ce sont deux réglages avancés du tRESTRequest.In JSON, the id attribute becomes a key and the numeric values lose their quotes: these are two advanced settings of the tRESTRequest.
Même route : le tJavaRow range 200 ou 404 dans globalMap, et le code du tRESTResponse est << custom >>, ((Integer) globalMap.get("status")).Same route: the tJavaRow stores 200 or 404 in globalMap, and the code of the tRESTResponse is << custom >>, ((Integer) globalMap.get("status")).
> GET http://localhost:8088/clients/99
> Accept: application/json
< HTTP 404 Not Found
< content-type: application/json
< transfer-encoding: chunked
{"error":{"message":"Unknown client 99"}}
Une route de création : code << custom >> 201 et un en-tête "Location".A creation route: << custom >> code 201 and a "Location" header.
> 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>
Le même service, appelé avec Accept: application/json : un client (/clients/2), une liste d'un client (?city=Lyon) et une liste de deux (?city=Paris). Le document de la liste est <clients><client>…</client>…</clients>.The same service, called with Accept: application/json: one client (/clients/2), a list of one client (?city=Lyon) and a list of two (?city=Paris). The document of the list is <clients><client>…</client>…</clients>.
Réglages par défautDefault settings
{"client":{"id":2,"name":"Grace Petit","city":"Lyon"}}
{"clients":{"client":{"id":2,"name":"Grace Petit","city":"Lyon"}}}
{"clients":{"client":[{"id":1,"name":"Ada Martin","city":"Paris"},{"id":3,"name":"Linus Morel","city":"Paris"}]}}Retirer la racine de la réponse JSON cochéeDrop JSON Response Root checked
{"id":2,"name":"Grace Petit","city":"Lyon"}
{"client":{"id":2,"name":"Grace Petit","city":"Lyon"}}
{"client":[{"id":1,"name":"Ada Martin","city":"Paris"},{"id":3,"name":"Linus Morel","city":"Paris"}]}
Clés de tableaux JSON : "client"JSON Array Keys: "client"
{"client":[{"id":2,"name":"Grace Petit","city":"Lyon"}]}
{"clients":{"client":[{"id":2,"name":"Grace Petit","city":"Lyon"}]}}
{"clients":{"client":[{"id":1,"name":"Ada Martin","city":"Paris"},{"id":3,"name":"Linus Morel","city":"Paris"}]}}
La clé s'applique partout où le nom apparaît : la réponse d'un seul client, dont la racine s'appelle aussi client, devient elle aussi un tableau. Convertir les valeurs JSON en chaînes du tRESTRequest :The key applies wherever the name appears: the response of a single client, whose root is also named client, becomes an array too. Convert JSON values to String of the tRESTRequest:
{"client":{"id":"2","name":"Grace Petit","city":"Lyon"}}
Route GET "/count" qui produit JSON ; type de corps Chaîne de caractères ; le tJavaRow écrit le JSON lui-même : output_row.body = "{\"count\":3}";GET "/count" route that produces JSON; String body type; the tJavaRow writes the JSON itself: output_row.body = "{\"count\":3}";
> GET http://localhost:8088/clients/count
> Accept: application/json
< HTTP 200 OK
< content-type: application/json
< content-length: 11
{"count":3}La chaîne part telle quelle : aucun des réglages JSON ne s'y applique, et rien ne vérifie qu'elle est du JSON valide.The string leaves as it is: none of the JSON settings applies to it, and nothing checks that it is valid JSON.
Route GET "/export" qui produit tous ; type de corps Byte[] ; trois en-têtes : "Content-Type" "text/csv", "Content-Disposition" "attachment; filename=clients.csv", "Set-Cookie" "session=abc123".GET "/export" route that produces any; Byte[] body type; three headers: "Content-Type" "text/csv", "Content-Disposition" "attachment; filename=clients.csv", "Set-Cookie" "session=abc123".
> GET http://localhost:8088/clients/export < HTTP 200 OK < content-disposition: attachment; filename=clients.csv < content-type: text/csv < set-cookie: session=abc123;Version=1 < content-length: 21 id;name 1;Ada Martin
Le tFixedFlowInput produit trois lignes, le tJavaRow en fait trois documents <client>. Case Flux de la route cochée :The tFixedFlowInput produces three rows, the tJavaRow turns them into three <client> documents. Streaming box of the route checked:
> GET http://localhost:8088/clients
> Accept: application/xml
< HTTP 200 OK
< content-type: application/xml
< transfer-encoding: chunked
<wrapper><client><id>1</id><name>Ada Martin</name></client><client><id>2</id><name>Grace Petit</name></client><client><id>3</id><name>Linus Morel</name></client></wrapper>
> GET http://localhost:8088/clients
> Accept: application/json
< HTTP 200 OK
< content-type: application/json
< transfer-encoding: chunked
[{"client":{"id":1,"name":"Ada Martin"}},{"client":{"id":2,"name":"Grace Petit"}},{"client":{"id":3,"name":"Linus Morel"}}]
En XML, la réponse n'a pas de déclaration <?xml …?>.In XML, the response has no <?xml …?> declaration.
Le composant déclare NB_LINE (After, Integer), mais son modèle ne la renseigne pas : elle reste nulle. Pour compter les réponses, comptez dans le flux.The component declares NB_LINE (After, Integer), but its template does not fill it: it stays null. To count the responses, count in the flow.
((Integer) globalMap.get("tRESTResponse_1_NB_LINE")) // null
Le job de l'exemple précédent, case Flux décochée. Le client ne reçoit que la première ligne, avec un code 200 :The job of the previous example, Streaming box unchecked. The client only receives the first row, with a 200 code:
> GET http://localhost:8088/clients > Accept: application/xml < HTTP 200 OK < content-type: application/xml < transfer-encoding: chunked <?xml version="1.0" encoding="UTF-8"?> <client><id>1</id><name>Ada Martin</name></client>
L'erreur n'apparaît que dans la console du service (nom du job remplacé par MyService, pile abrégée) :The error only appears in the console of the service (job name replaced with MyService, shortened stack):
Exception in component tRESTResponse_1 (MyService) java.lang.RuntimeException: Rest response already sent. at demo.myservice_0_1.MyService.tRESTRequest_1_LoopProcess(MyService.java:2206) at demo.myservice_0_1.MyService$RestServiceProviderImpl4TalendJob.processRequest(MyService.java:458) at demo.myservice_0_1.MyService$RestServiceProviderImpl4TalendJob.allClients(MyService.java:578) …
Pour renvoyer une liste, réunissez les lignes en un seul document avant le tRESTResponse (tXMLMap avec un élément de boucle et All in one, agrégation dans un tJavaFlex), ou cochez Flux sur la route.To return a list, gather the rows into a single document before the tRESTResponse (tXMLMap with a loop element and All in one, aggregation in a tJavaFlex), or check Streaming on the route.
Par défaut, la liste d'un seul client sort comme un objet et celle de deux comme un tableau (voir Les réglages JSON) : le programme qui lit la réponse doit gérer les deux formes. Déclarez l'élément répété dans Clés de tableaux JSON, en lui donnant un nom qui ne sert pas ailleurs.By default, the list of a single client comes out as an object and the list of two as an array (see The JSON settings): the program that reads the response has to handle both shapes. Declare the repeated element in JSON Array Keys, giving it a name that is not used elsewhere.
Une route produisant tous, appelée sans en-tête Accept, a renvoyé un corps de type chaîne sous content-type: application/octet-stream. Choisissez un type dans Produit, ou ajoutez un en-tête "Content-Type" à la réponse.A route producing any, called with no Accept header, returned a string body under content-type: application/octet-stream. Choose a type in Produces, or add a "Content-Type" header to the response.
Pour une chaîne ou des octets, rien ne relie le contenu au type annoncé : une chaîne JSON renvoyée à un client qui demande application/xml part sous content-type: application/xml. Limitez Produit au type que le flux écrit vraiment.For a string or bytes, nothing ties the content to the announced type: a JSON string returned to a client that asks for application/xml leaves under content-type: application/xml. Restrict Produces to the type the flow really writes.
Dans un job sans tRESTRequest, le composant ne fait rien d'autre qu'écrire [WARN] nonsense: tRESTResponse component used without tRESTRequest component on the job sur la sortie d'erreur. Exécuté en dehors du traitement d'une requête, il échoue avec Not received rest request yet. Ces deux cas sont lus dans le modèle, sans essai.In a job without a tRESTRequest, the component does nothing but write [WARN] nonsense: tRESTResponse component used without tRESTRequest component on the job to the error output. Run outside the processing of a request, it fails with Not received rest request yet. Both cases are read in the template, with no run.
Une exception dans le flux donne au client un 500 dont le corps est le message de l'exception, et un flux sans réponse un 404 vide. Prévoyez un tRESTResponse pour chaque issue (introuvable, requête invalide) et, pour les requêtes mal formées, un autre au bout du lien Appel incorrect du tRESTRequest.An exception in the flow gives the client a 500 whose body is the message of the exception, and a flow without a response an empty 404. Plan a tRESTResponse for each outcome (not found, invalid request) and, for malformed requests, another one at the end of the Wrong Call link of the tRESTRequest.
Avec un Document, le même flux sert les clients XML et les clients JSON, et la conversion échappe les caractères pour vous. Gardez la chaîne pour un format que vous maîtrisez entièrement (JSON écrit par un tWriteJSONField, texte, HTML).With a Document, the same flow serves the XML clients and the JSON clients, and the conversion escapes the characters for you. Keep the string for a format you fully control (JSON written by a tWriteJSONField, text, HTML).
tRESTRequest · publier le service et ses routespublish the service and its routestRESTClient · appeler le service depuis un autre jobcall the service from another jobtESBProviderResponse · répondre à une opération SOAPanswer a SOAP operationtJavaRow · préparer le corps en Javaprepare the body in Java