No ‘Access-Control-Allow-Origin’ header is present on the requested Drupal 8.x rest APIs

Reading time: 4 minutes

Problem

Facing No ‘Access-Control-Allow-Origin’ header is present on the requested Drupal 8.x error message on browser while working with Drupal Rest API’s

CORS policy
CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource Drupal REST API's

Final output

After setting up the CORS policy for Drupal Rest API’s we can successfully able to make it work on bowers and would not have the below error message again.

Access to XMLHttpRequest at ‘example’ from origin ‘example’ has been blocked by CORS policy. No ‘Access-Conrol-Allow-Origin’ header is present on the requested resource.

Most of the time you wonder when working with Drupal rest APIs in your application and this error message creeps up 😀

Usually this error occurs when the client URL and server URL don’t match (including the port number)
So to resolve the problem we need to enable the service for CORS

Why?
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

What is Drupal Advanced CORS module?
Cross-origin resource sharing (CORS) – the module provides possibility to customize settings CORS by path patterns.
All settings will be saved in configs.

So, the solution is to enabling CORS and allow Access-Control-Allow-Origin authorization for origin domains using Advanced CORS module in Drupal 8.x site.

Let’s get started 🙂

Solution

1. Get Advanced CORS module by visiting here and then install the module in your Drupal 8.x site.

Note: The URL to install the module is
https://ftp.drupal.org/files/projects/advanced_cors-8.x-1.1.tar.gz

Install Advanced CORS module Drupal 8.x site
Install Advanced CORS module Drupal 8.x site

2. Enable the Advanced CORS module.

Enable Advanced CORS module
Enabling Advanced CORS module

3. Now we have to add route configuration in our CORS settings.
Configuration -> Web services -> CORS Settings
Then click on Add Route configuration button

Add Route configuration from CORS settings
Add Route configuration from CORS settings

4. Adding CORS route configuration settings as per your desired requirements.
1. Name for the route configuration.
2. Patterns
3. Allowed headers
4. Allowed methods
5. Allowed origins

Then click on Save

Adding CORS configuration
Adding CORS configuration

Finally after successfully configured the CORS route now go to your browser and try to hit the Drupal rest API’s end point and you will see the response is showing successfully 🤩

Success getting API response
Success response after CORS settings for Drupal rest API's

Congratulations now you can work with Drupal Rest APIs without No ‘Access-Control-Allow-Origin’ header is present on the requested Drupal 8.x error message on browser ❤️

Drupal 8.x Delete content node via rest API

Reading time: 2 minutes

Problem

How to Delete Article or any other custom content type node in Drupal 8.x site via rest API by using REST module.

Final output

At the end we will be able to delete an Article node content using rest API in Drupal 8.x

Let’s jump to achieve our goal to delete an article content node or data via rest API in Drupal 8 site.

NOTE: Make sure all the configurations for JSON:API and REST modules has been setup correctly by visiting here

Solution

1. Open up the API testing tool, We are going to test it through rest API using Postman.

Delete Article content type API

* Request:
Method:
DELETE


URL:
{{BASE_URL}}/node/[nid]?_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

* Response
HTTP 204 (No content) response with Empty response body.
The article with {{nid}} is now deleted.

Delete article content type node Response postman
Delete Article content type node via rest API Postman response

Awesome we have done it 🥰

Finally, just go to your admin panel and see inside content list you will see the deleted content is no more there, isn’t it so easy 😉

Congratulations now we can Delete Article or any other content type node via rest API by REST module in Drupal 8.x site 🙂

Drupal 8.x Update existing content or data with rest API

Reading time: 3 minutes

Problem

How to Update or PATCH existing Article or any other custom content type with image in Drupal 8.x site via rest API by using JSON:API and REST module.

Final output

At the end we will be able to Update an Article node content with image field using rest API by JSON:API in Drupal 8.x site.

Prerequisite

Before updating or PATCH Article content type with image, we have to upload the image file correctly and then we link that image with article update HTTP method via rest API.

If you want to make sure, How to Post or upload files by JSON rest API in Drupal 8.x site check it out

The process to updating or PATCH a content with image via rest API in Drupal 8.x site is, to upload the image file first and then in uploaded file response we will get fid value.

So, if you already did that, then just keep the fid value with you and we will use it in a while.

If you are ready until there, then let’s jump to achieve our goal to Update article content via rest API in Drupal 8 site.

NOTE: Also make sure all the configurations for JSON:API and REST modules has been setup correctly by visiting Prerequisite article.

Solution

1. Open up the API testing tool, We are going to test it through rest API using Postman.

Update Article content type API

* Request:
Method:
PATCH


URL:
{{BASE_URL}}/node/[nid]?_format=hal_json
* nid:
This is the node Id of the content you want to update.

Headers:
* Authorization: Basic <credential>  
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/node/article"
        }
    },
    "title":{
        "value":"Updated Article"
    },
    "field_image": [
        {
            "target_id": 4
        }
    ]
}

NOTE:
* Put your fid value which you can get in response of uploaded file rest API in target_id, or if you uploaded file manually then put nid of file.
* Image is optional and you can update record without image field by just remove field_image from API body request.

To get the machine name for image field in Article content type in Drupal 8.x site.

Go to Structure -> Content types -> Article -> Manage fields  and there you can see all the machine names for fields e-g field_image for article image.

Get machine name for image field in content type article Drupal 8 site
Get machine name for image field in Article content type

* Response

{
    "_links": {
        "self": {
            "href": "https://dev-solution-spirit-cms.pantheonsite.io/node/4?_format=hal_json"
        },
        "type": {
            "href": "https://dev-solution-spirit-cms.pantheonsite.io/rest/type/node/article"
        },
        "https://dev-solution-spirit-cms.pantheonsite.io/rest/relation/node/article/revision_uid": [
            {
                "href": "https://dev-solution-spirit-cms.pantheonsite.io/user/1?_format=hal_json"
            }
        ],
        "https://dev-solution-spirit-cms.pantheonsite.io/rest/relation/node/article/uid": [
            {
                "href": "https://dev-solution-spirit-cms.pantheonsite.io/user/1?_format=hal_json",
                "lang": "en"
            }
        ],
        "https://dev-solution-spirit-cms.pantheonsite.io/rest/relation/node/article/field_image": [
            {
                "href": "https://dev-solution-spirit-cms.pantheonsite.io/file/4?_format=hal_json",
                "lang": "en"
            }
        ]
    },
    "nid": [
        {
            "value": 4
        }
    ],
    "uuid": [
        {
            "value": "2d9e718e-2b6f-4e9e-9afd-3469fab491de"
        }
    ],
    "vid": [
        {
            "value": 4
        }
    ],
    "langcode": [
        {
            "value": "en",
            "lang": "en"
        }
    ],
    "type": [
        {
            "target_id": "article"
        }
    ],
    "revision_timestamp": [
        {
            "value": "2020-06-21T14:30:17+00:00",
            "format": "Y-m-d\\TH:i:sP"
        }
    ],
    "_embedded": {
        "https://dev-solution-spirit-cms.pantheonsite.io/rest/relation/node/article/revision_uid": [
            {
                "_links": {
                    "self": {
                        "href": "https://dev-solution-spirit-cms.pantheonsite.io/user/1?_format=hal_json"
                    },
                    "type": {
                        "href": "https://dev-solution-spirit-cms.pantheonsite.io/rest/type/user/user"
                    }
                },
                "uuid": [
                    {
                        "value": "f2433a47-8026-4811-860a-a8dd3e23b28b"
                    }
                ]
            }
        ],
        "https://dev-solution-spirit-cms.pantheonsite.io/rest/relation/node/article/uid": [
            {
                "_links": {
                    "self": {
                        "href": "https://dev-solution-spirit-cms.pantheonsite.io/user/1?_format=hal_json"
                    },
                    "type": {
                        "href": "https://dev-solution-spirit-cms.pantheonsite.io/rest/type/user/user"
                    }
                },
                "uuid": [
                    {
                        "value": "f2433a47-8026-4811-860a-a8dd3e23b28b"
                    }
                ],
                "lang": "en"
            }
        ],
        "https://dev-solution-spirit-cms.pantheonsite.io/rest/relation/node/article/field_image": [
            {
                "_links": {
                    "self": {
                        "href": "https://dev-solution-spirit-cms.pantheonsite.io/file/4?_format=hal_json"
                    },
                    "type": {
                        "href": "https://dev-solution-spirit-cms.pantheonsite.io/rest/type/file/image"
                    }
                },
                "uuid": [
                    {
                        "value": "25d66eec-ee67-4353-b4ef-0141a9b4858e"
                    }
                ],
                "lang": "en",
                "alt": null,
                "title": null,
                "width": 700,
                "height": 576
            }
        ]
    },
    "status": [
        {
            "value": true,
            "lang": "en"
        }
    ],
    "title": [
        {
            "value": "Updated Article",
            "lang": "en"
        }
    ],
    "created": [
        {
            "value": "2020-06-21T14:30:17+00:00",
            "lang": "en",
            "format": "Y-m-d\\TH:i:sP"
        }
    ],
    "changed": [
        {
            "value": "2020-07-21T15:59:12+00:00",
            "lang": "en",
            "format": "Y-m-d\\TH:i:sP"
        }
    ],
    "promote": [
        {
            "value": true,
            "lang": "en"
        }
    ],
    "sticky": [
        {
            "value": false,
            "lang": "en"
        }
    ],
    "default_langcode": [
        {
            "value": true,
            "lang": "en"
        }
    ],
    "revision_translation_affected": [
        {
            "value": true,
            "lang": "en"
        }
    ],
    "path": [
        {
            "alias": null,
            "pid": null,
            "langcode": "en",
            "lang": "en"
        }
    ],
    "comment": [
        {
            "status": 2,
            "cid": 0,
            "last_comment_timestamp": 1592749817,
            "last_comment_name": null,
            "last_comment_uid": 1,
            "comment_count": 0,
            "lang": "en"
        }
    ]
}

Update or PATCH article content type with image Rest API in Drupal 8.x
Update Article content with image via rest API Postman test

Awesome we have done it, At last just go to your admin panel and see inside content list you will find the updated content with image, isn’t it so easy 😉

Congratulations now we can update or PATCH Article or any other content type with image as (optional) via rest API by JSON:API module in Drupal 8.x site 🙂