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

**URL:** <https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905>\
**Category:** API & Programming\
**Created:** [August 4, 2023, 8:39pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905 "2023-08-04T20:39:19Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![AlexH](https://avatars.discourse-cdn.com/v4/letter/a/6f9a4e/32.png) [@AlexH](https://community.fibery.io/u/AlexH)\
**Post date:** [August 4, 2023, 8:39pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/1 "2023-08-04T20:39:19Z")

</div>

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:

```auto

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):

```auto
{"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

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

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

```

---

<div class="post-metadata">

**Author:** ![Chr1sG](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/chr1sg/32/3941_2.png) [@Chr1sG](https://community.fibery.io/u/Chr1sG)\
**Post date:** [August 5, 2023, 9:19am UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/2 "2023-08-05T09:19:39Z")

</div>

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

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:

> [@AlexH](#):
>
> I have a files attached to the entity, how I can send all them through the API?

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

---

<div class="post-metadata">

**Author:** ![AlexH](https://avatars.discourse-cdn.com/v4/letter/a/6f9a4e/32.png) [@AlexH](https://community.fibery.io/u/AlexH)\
**Post date:** [August 6, 2023, 3:26am UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/3 "2023-08-06T03:26:33Z")

</div>

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

 ![Screenshot 2023-08-05 at 11.23.14 PM](https://us1.discourse-cdn.com/flex020/uploads/fibery/original/2X/0/0deb220827b6915266ccdd6647f984b0460c72a4.png)

---

<div class="post-metadata">

**Author:** ![Chr1sG](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/chr1sg/32/3941_2.png) [@Chr1sG](https://community.fibery.io/u/Chr1sG)\
**Post date:** [August 6, 2023, 2:00pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/4 "2023-08-06T14:00:23Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Chr1sG](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/chr1sg/32/3941_2.png) [@Chr1sG](https://community.fibery.io/u/Chr1sG)\
**Post date:** [August 7, 2023, 1:05pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/5 "2023-08-07T13:05:09Z")

</div>

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:

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

```

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

---

<div class="post-metadata">

**Author:** ![AlexH](https://avatars.discourse-cdn.com/v4/letter/a/6f9a4e/32.png) [@AlexH](https://community.fibery.io/u/AlexH)\
**Post date:** [August 7, 2023, 1:32pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/6 "2023-08-07T13:32:58Z")

</div>

Hi Chris! Thank you so much, it works!

---

<div class="post-metadata">

**Author:** ![Chr1sG](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/chr1sg/32/3941_2.png) [@Chr1sG](https://community.fibery.io/u/Chr1sG)\
**Post date:** [August 7, 2023, 2:48pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/7 "2023-08-07T14:48:42Z")

</div>

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

```auto
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:

 ![image](https://us1.discourse-cdn.com/flex020/uploads/fibery/original/2X/f/fc18f9019b631209071080d1ea7f62b689a5edec.png)

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:

```auto
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 🤷

Let us know how you get on.

---

<div class="post-metadata">

**Author:** ![AlexH](https://avatars.discourse-cdn.com/v4/letter/a/6f9a4e/32.png) [@AlexH](https://community.fibery.io/u/AlexH)\
**Post date:** [August 7, 2023, 4:09pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/8 "2023-08-07T16:09:36Z")

</div>

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/](https://carrier.superdispatch.com/oauth/token/)’, {  
headers: {  
‘Content-Type’: ‘application/x-www-form-urlencoded’,  
‘Authorization’: authHeader,  
},  
body: ‘grant\_type=client\_credentials’,  
});

---

<div class="post-metadata">

**Author:** ![Chr1sG](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/chr1sg/32/3941_2.png) [@Chr1sG](https://community.fibery.io/u/Chr1sG)\
**Post date:** [August 7, 2023, 5:17pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/9 "2023-08-07T17:17:53Z")

</div>

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).

---

<div class="post-metadata">

**Author:** ![AlexH](https://avatars.discourse-cdn.com/v4/letter/a/6f9a4e/32.png) [@AlexH](https://community.fibery.io/u/AlexH)\
**Post date:** [August 7, 2023, 6:54pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/10 "2023-08-07T18:54:09Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Chr1sG](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/chr1sg/32/3941_2.png) [@Chr1sG](https://community.fibery.io/u/Chr1sG)\
**Post date:** [August 7, 2023, 9:08pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/11 "2023-08-07T21:08:25Z")

</div>

> [@AlexH](#):
>
> After 2 days of testing and trying different scripts I was able to fix it and get a token!

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

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 ☹

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) 😬

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 😕

---

<div class="post-metadata">

**Author:** ![AlexH](https://avatars.discourse-cdn.com/v4/letter/a/6f9a4e/32.png) [@AlexH](https://community.fibery.io/u/AlexH)\
**Post date:** [August 8, 2023, 3:35pm UTC](https://community.fibery.io/t/how-to-send-a-file-from-fibery-through-the-api-to-another-service-and-write-the-response-back-to-fibery/4905/12 "2023-08-08T15:35:31Z")

</div>

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

 ![Screenshot 2023-08-08 at 4.24.54 PM](https://us1.discourse-cdn.com/flex020/uploads/fibery/original/2X/7/758b4b061d760d98126b3f087fed01b38e8de537.png)
