How to Post or upload files by JSON rest API in Drupal 8.x site

Reading time: 4 minutes

Problem

How to setup and Post files by JSON rest API web services in Drupal 8.x site.

Final output

By reading the article, we will be able upload files in our Drupal 8.x site through web services rest API.

Prerequisite

Before uploading files by rest API make sure we have correctly Setup Drupal 8.x site as JSON rest API using JSON:API and REST module.

File uploading with JSON:API?
File upload support has been added to JSON:API. This makes JSON:API as capable as Drupal core REST and also adds a new feature above and beyond core REST.

So, If you already did that then let’s dig deep into our goal to Post or upload files in Drupal 8.x site 🙂

Solution

1. Go to Configuration -> Web services -> JSON:API
Then check option “Accept all JSON:API create, read, update, and delete operations” and Save configuration

Change JSON API configuration to Accept all operations
Change JSON API configuration to Accept all operations

2. Now this time Go to Configuration -> Web services -> REST
Here we have to enable File rest resource by clicking Enable button.

Enable File from REST resources module
Enable File from REST resources module

3. Set HTTP methods, the available formats and authentication providers for File entity as below.

Set HTTP methods, formats and authentications
Set HTTP methods, formats and authentications

4. Install File Entity module which provides user interface to managing files.

To get the module visit the File Entity module site

To install Just copy the tar.gz file link address and go to Install new module paste the link and we are done 🙂

After installation its time to enable the File entity module, but when we try to enable we might requires the missing modules.

So, the solution is simple just install the missing modules, e-g In my case it was Token module

Install required missing modules for file entity

Now we can enable any required and missing module with File entity module.

5. Set uploaded files status as Permanent in File entity module. The purpose is, when later we create or Post content with image then it will not work until the uploaded file status is Permanent. By default it uploads in Temporary status mode.

To do that we have to access site Files using SFTP/FTP or if you are working in localhost just go to the below path.

Code -> modules –> file_entity -> src -> Normalizer and open FileEntityNormalizer.php file.

Scroll down to the bottom of file and add $entity->status = FILE_STATUS_PERMANENT; just above return $entity;

Finally its time for a good news, We are going to test it through rest API using Postman testing tool.

Upload image file API

* Request:
Method:
POST


URL:
{{BASE_URL}}/entity/file?_format=hal_json

Headers:
* Authorization: Basic <credentials> 
Basic authentication is where the username and password-based authentication takes place.
* X-CSRF-Token: We can get CSRF token in response of Login API.
To see how to get CSRF token in Drupal site
* Content-Type: application/hal+json


Body:

{
    "_links": {
        "type": {
            "href": "[BASE_URL]/rest/type/file/image"
        }
    },
    "filename": [
        {
            "value": "imagename.png"
        }
    ],
    "filemime": {
        "value": "image/png"
    },
    "uri": [
        {
            "value": "public://image.png"
        }
    ],
    "type": {
        "target_id": "file"
    },
    "data": [
        {
            "value": "[BASE64 ENCODED IMAGE VALUE]"
        }
    ]
}

NOTE:
* To upload video file just change in body _links -> type -> href to [BASE_URL]/rest/type/file/video, and other values respectively.

* For Encode image to base64, we can use the command tool, here is the link

Upload image file rest API request and response
Drupal 8.x upload files rest API request and response

* Response

{
    "_links": {
        "self": {
            "href": "https://dev-solution-spirit-cms.pantheonsite.io/file/3?_format=hal_json"
        },
        "type": {
            "href": "https://dev-solution-spirit-cms.pantheonsite.io/rest/type/file/image"
        }
    },
    "fid": [
        {
            "value": 3
        }
    ],
    "uuid": [
        {
            "value": "97b1050d-821d-4af3-8c96-65af2d3f091b"
        }
    ],
    "langcode": [
        {
            "value": "en"
        }
    ],
    "type": [
        {
            "target_id": "image"
        }
    ],
    "filename": [
        {
            "value": "imagename.jpg"
        }
    ],
    "uri": [
        {
            "value": "public://image.png",
            "url": "/sites/default/files/image.png"
        }
    ],
    "filemime": [
        {
            "value": "image/png"
        }
    ],
    "filesize": [
        {
            "value": 1951
        }
    ],
    "status": [
        {
            "value": true
        }
    ],
    "created": [
        {
            "value": "2020-05-05T21:28:07+00:00",
            "format": "Y-m-d\\TH:i:sP"
        }
    ],
    "changed": [
        {
            "value": "2020-05-05T21:28:07+00:00",
            "format": "Y-m-d\\TH:i:sP"
        }
    ],
    "data": [
        {
            "value": "R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGB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IL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw=="
        }
    ]
}


NOTE: In response, we will need fid value later when create or Post a content with uploaded file.

View the uploaded file by JSON rest API on Drupal 8.x admin site.

View uploaded file on Drupal admin site
View uploaded file on Drupal admin site

Congratulations now we can upload files by web services JSON:API module in Drupal 8.x site 🙂

Share your love with us 😉

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Leave a Reply