upload json file from app backend to the files page by the new file api

Avi_Ben_Zaken
Shopify Partner
18 0 6

Hey,

I need to upload a JSON file which created in the backend part of my app.

1) So I'm using stagedUploadsCreate to get the temp URL for uploading the file to- that part seems to working fine.

2) Then upload the file using fetch - here I think there is a problem, although I'm getting a 201 response with status "created".

When I try using form.append('file', fs.createReadStream(data)); I'm getting 412 precondition failed error.

3) The last step is calling the fileCreate mutation- here there is some issue, although I'm getting a 200 response but no new file URL in the result.

This is my code: 

async function addFileOS2(shopName, accessToken, data) {
    try {
        data = JSON.stringify(data.data);
        const query = JSON.stringify({
            query: `mutation {
        stagedUploadsCreate(
            input:{
            resource: FILE
            filename: "test.json"
            mimeType: "JSON"
            httpMethod: POST
        }
            ) 
            {
                stagedTargets {
                    resourceUrl
                    url
                    parameters {
                      name
                      value
                    }
                  }
                  userErrors {
                    field
                    message
                  }
            }
        }`
        });

        let response = await fetch(`https://${shopName}/admin/api/2021-07/graphql.json`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                "X-Shopify-Access-Token": accessToken,
                'Access-Control-Allow-Origin': '*'
            },
            body: query
        })

        const responseJson = await response.json();
        const { url, parameters, resourceUrl } = responseJson.data.stagedUploadsCreate.stagedTargets[0];
        var FormData = require('form-data');
        var fs = require('fs');

        var form = new FormData();
        parameters.forEach(({ name, value }) => {
            form.append(name, value)
        })
		
        form.append('file', data);//fs.createReadStream(data));

        const response2 = await axios(url, {
            headers: {
                'Content-Length': data.length,
            },
            method: 'POST',
            body: form,
        })

        query = JSON.stringify({
            query: `mutation {
        fileCreate(
            files:{
            originalSource: "${response2.headers.get('location')/*resourceUrl*/}" //tried also using resourceUrl  
        }) {
            files {
              alt
              createdAt
            }
            userErrors {
              code
              field
              message
            }
          }
        }
    }`
        });

        response = await fetch(`https://${shopName}/admin/api/2021-07/graphql.json`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                "X-Shopify-Access-Token": accessToken,
                'Access-Control-Allow-Origin': '*'
            },
            body: query
        })
        if (!response.ok) {
            throw ('File could not be uploaded.')
        }
        console.log(response);
    }
    catch (err) {
        scriptLogger.error('deleteFile failed', { err: `${err}` });
    }
}

 

If you have any suggestions, I would be happy to hear about,

Thanks

Replies 2 (2)
GrahamS
Shopify Staff (Retired)
Shopify Staff (Retired)
193 36 52

Hey @Avi_Ben_Zaken ,

Can I ask you to provide an x-request-id for this interaction? Your code looks good at a glance, so I'd like to see what is happening here on our side.

Best,

Graham

Graham S | API Support @ Shopify
- Was my reply helpful? Click Like to let me know!
- Was your question answered? Mark it as an Accepted Solution
- To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

simpatico
New Member
3 0 0

@Avi_Ben_Zaken - Have you been able to find a solution for this? I'm trying to do something similar (though using PHP to create the JSON and upload it to Shopify). 

I tried using the Asset API, but it appears to only allow you to upload a graphic file (not JSON). 

Thanks!