# HTTP Agent Request Examples Some examples for LOC's [HTTP Agent](https://hackmd.io/Uj-tC7l9Q82VyGr8R5PL2Q#HTTP-Agents). :::info You can use online services like ++[httpbin.org/anything](https://httpbin.org/anything)++ or ++[Postman Echo](https://www.postman.com/postman/workspace/published-postman-templates/documentation/631643-f695cab7-6878-eb55-7943-ad88e1ccfd65)++ for testing HTTP requests. They essentially return anything you send them. ::: ## GET Request with QueryString ```javascript // query params in the form of object const url = "https://myserver/myservice" const query = { name: "Arthur", age: 42 } // transform object to QueryString // e.g. name=Arthur&age=42 const queryString = new URLSearchParams(query).toString(); // send GET request with querystring const response = await ctx.agents.http.get( `${url}?${queryString}`, // url {}, // headers "None", // no content type null, // body ); const resp_body = JSON.parse(new TextDecoder().decode(response.body)); // do something with the response body ``` ## POST Request with a File To send a text file (eg. txt, html, xml, csv) through a POST request, you need to set the header and body to a specific format: ```javascript const url = "https://myserver/myservice" // input name and file name const fileName = "test_file"; const fileFullName = "test_file.txt"; const fileType = "text/plain"; // change it to other HTTP content types if needed // mock-up text file content (using template literal) // you can replace it with contents read from request body or file storage agent, etc. const filedata = `Hello World! This is the second row.`; // -------------------------------------------------- // multipart headers // use task id as the boundary word const boundaryValue = ctx.task.taskId.id; const headers = { "Content-Type": `multipart/form-data; boundary=${boundaryValue}`, }; // multipart body template const body = `--${boundaryValue}` + "\r\n" + `Content-Disposition: form-data; name=${fileName}; filename=${fileFullName}` + "\r\n" + `Content-Type: ${fileType}` + "\r\n\r\n" + `${filedata}` + "\r\n" + `--${boundaryValue}--` + "\r\n"; // send post request with the file const response = await ctx.agents.http.post( url, // url headers, // headers "PlantText", // does not matter here new TextEncoder().encode(body), // body ); const resp_body = JSON.parse(new TextDecoder().decode(response.body)); // do something with the response body ``` :::info The **boundary word** can be any string but *must not* exceed 70 characters in length and consists only of 7-bit US-ASCII characters. You can also send multiple files in one request by modifying this example (see: ++[HTTP POST method](https://developer.mozilla.org/zh-TW/docs/Web/HTTP/Methods/POST)++). ::: ## User Authorization (LOC CLI only) Some HTTP APIs require you to fill in authentication data in the ```Authorization``` header. For safety reasons, we will store these secret information in the profile. Right now this only works with [LOC CLI](https://hackmd.io/4LIsNIuWQnuR70JMeuBAEA?view). 1. First add the user account and password for the authorization: ```yaml baseURL: https://api.loc.xxxxx namespace: xxxxxxxx authURL: https://auth.xxxxx.xxxxxxx/auth realm: xxxxx clientId: xxxxx-xxxxx-xxxxx # authorization info user: user pass: 1234 ``` The ```user``` and ```pass``` field will be passed into the data process under ```process.env``` variable. 2. Update the profile: ```bash loc profile set -f <profile name>.yaml -p <profile name> ``` 3. Write code: ```javascript const url = "https://myserver/myservice" // example payload to be sent const data = { content: "some data to be send" }; // use Web API to encode "user:password" to Base64 string const authToken = btoa(`${process.env.user}:${process.env.pass}`); // setting authorization header const headers = { "Authorization": `Basic ${authToken}`, } // send post request with a JSON payload const response = await ctx.agents.http.post( url, // url headers, // headers "Json", // content type new TextEncoder().encode(JSON.stringify(data)), // body ); const resp_body = JSON.parse(new TextDecoder().decode(response.body)); // do something with the response body ``` :::info ```Basic``` is the most common authentication scheme. See ++[The general HTTP authentication framework](https://developer.mozilla.org/zh-TW/docs/Web/HTTP/Authentication#authentication_schemes)++ for available options. If you are using LOC Studio, you can instead encode ```user:password``` first then pass them via an API route. How to do it outside the data process depends on your development environment. For example, if you are using JavaScript and Node.js locally, you can do it like this: ```javascript const authToken = Buffer.from(`${user}:${password}`).toString('base64'); ``` ::: ###### tags: `LOC Studio` `LOC CLI`