How to send a file from Fibery through the API to another service and write the response back to Fibery

Hello, I’m trying to integrate Fibery with another service through the API.
I have working script that creates a driver with name from entity:


const http = context.getService("http");
const fibery = context.getService('fibery');
const entity = args.currentEntities[0];
console.log(entity);

const response = await http.postAsync("https://xxxxxxxxxxxxxxxx/drivers/", {

'headers': { 'Authorization': 'Bearer ' + entity['Token'] }, 'body': {

"name": entity['LOAD ID'],
"email": '[sadfads2f@adsf.df]',
"phone": '333-999-0707',
"cars": '3'

}})
console.log(response);

And I’m receiving such response from the service (with driver ID just created in their system):

{"meta":{"code":201,"request_id":"827f8c1f-38c1-4384-a9f4-91ce0151383c"},"data":{"id":214803,"name":"12884616","phone":"+1333-999-0707","email":"[sadfa3ds2f@adsf.df]","cars":3}}

Is there any chance to save “id”:214803 from the response back to the entity (this field will have name “Driver id”)

And second question, I can’t find information how to send attached files through the API. I have a files attached to the entity, how I can send all them through the API?

API docs in the system I’m trying to integrate with Fibery says that request should look like this

POST xxxxxxxxxxxxxxxxxx/attachments/
Content-Type: multipart/form-data

{
"name": <string>,
"file": <file> 
}

Based on the example response you provided, you would probably use the following code to extract the relevant id:

const response_id = response['data']['id']

Then you can use the following to update the entity:

await fibery.updateEntity(entity.type, entity.id, {'Field Name': response_id});

where Field Name is the name of whatever field you want to put the ID into.

For this:

let me do a bit of experimenting and get back to you (probably on Monday I’m afraid)

1 Like

Hi Chris, thank you so much for the an answer!
I’m testing it, but received an error

It’s probably worth hopping on a call and debugging together. Do you want to book a slot in my calendar and hopefully we can figure it out.

Hi @AlexH
I think I have realised why my solution did not work: response is a string, and needs to be converted to an object in order for the id to be extracted.

Try this:

const responseObj = JSON.parse(response);
const response_id = responseObj['data']['id'];

I’ll get back to you again later with the files question.

Hi Chris! Thank you so much, it works!

For sending a file (or several) that is attached to a Fibery entity, I reckon you’ll need to write code something like this:

const http = context.getService("http");
const fibery = context.getService('fibery');

for (const entity of args.currentEntities) {

    const entityWithExtraFields = await fibery.getEntityById(entity.type, entity.id, ['Files', 'Token', 'LOAD ID']);
    console.log(entityWithExtraFields);

    for (const file of entityWithExtraFields['Files']) {
        const fileWithSecret = await fibery.getEntityById("fibery/file", file['id'], ["Secret", "Name", "Content Type"]);
        const fileUrl = "http://XXXX.fibery.io/api/files/" + fileWithSecret["Secret"];
        console.log(fileUrl);
        const f = await http.getAsync(fileUrl, { 'headers': { 'Authorization': 'Token an-api-token-for-your-workspace'}});
        console.log(f);

        const response = await http.postAsync("https://xxxxxxxxxxxxxxxx/files/", {
            'headers': { 'Authorization': 'Bearer ' + entity['Token'] }, 'body': {
                "name": entity['LOAD ID'],
                "file": f
            }
        })
        const responseObj = JSON.parse(response);
        console.log(responseObj);
    }
}

replacing xxx’s and an-api-token-... with whatever is appropriate.

FYI: Fibery API keys are generated in settings:

The code for the API call to the third party service may not be formed perfectly correctly, since I don’t know enough details. You will probably need to experiment (with postman or whatever) to confirm the correct syntax for this bit:

const response = await http.postAsync("https://xxxxxxxxxxxxxxxx/files/", {
    'headers': { 'Authorization': 'Bearer ' + entity['Token'] },
    'body': {
        "name": entity['LOAD ID'],
        "file": f
    }
})

Maybe the headers aren’t needed :person_shrugging:

Let us know how you get on.

1 Like

Thank you Chris, I’ll try to test it!

Now I’m stuck on getting a Token through the Fibery script. As you remember I can get it through the postman, but we need to get it through the fibery by schedule.
This is part of the script, I was told to use either BTOA or Buffer, but non of these are working, it returns boa is not defined or buffer is not defined

//const authHeader = 'Basic ’ + btoa(“clientId+clientSecret”).toString(‘base64’);
//const authHeader = 'Basic ’ + Buffer.from(“clientId+clientSecret”).toString(“base64”);
const authHeader = Buffer.from(“clientId+clientSecret”).toString(“base64”);
const response = await http.postAsync(‘https://carrier.superdispatch.com/oauth/token/’, {
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded’,
‘Authorization’: authHeader,
},
body: ‘grant_type=client_credentials’,
});

Can you show what works in postman (with screen grabs, blurred to hide sensitive info if needed) and we can figure out how to reproduce in Fibery.
Alternatively/as well, can you send the relevant extracts of the api documentation for the third party (super dispatch i presume).

After 2 days of testing and trying different scripts I was able to fix it and get a token! It was necessary to pass client id and client secret in ‘body’ not in headers -Authorization

Sounds like you’re becoming a fully-fledged SW dev! :stuck_out_tongue_winking_eye:

With respect to the code I provided for file handling, my colleagues (who are smarter than I am) have told me that the code I posted probably only works for some file types and for limited sizes of files :frowning:

I’m now not sure if it’s possible to transfer a file from Fibery to another tool, unless perhaps the other tool has an API call that allows you to attach/upload a file from a url, rather than by sending a blob/file-stream) :grimacing:

At some point v soon (if not already) we’ll reach the limit of my experience/knowledge/skills in this area, and I might have to pass the baton to someone else :confused:

Hi Chris, thank you so much for your help!

So we are able to get the URL of the file using the script, and I’m trying to get the data or content of the file and play with it, but the response for f2 and f3 returns “undefined” - any suggestions?

const f = await http.getAsync(fileUrl, { ‘headers’: { ‘Authorization’: ‘Token xxxxx’ } });
console.log(f);
const f2 = f.data;
const f3 = f.content;
console.log(f2);
console.log(f3);

Is there any chance to create\receive FormData from the file? Something like this?
const formData = new FormData();
formData.append(‘name’, entity[‘LOAD ID’]);
formData.append(‘file’, new Blob([f2]), fileWithSecret[‘Name’]);

When I’m trying to send request from Postman - it using FormData