Search code examples
drupaldrupal-8drupal-entities

Cannot create a new entity (created with ECK) through API using REST module


Here is my situation: I am using the ECK module with Drupal 8 to create entities and bundles, and the new REST core module to create API features.

I have installed the REST_UI module, and I enabled the route for the entity I am interested in.

Here's my issue: I created an entity type and a bundle with ECK, and I can then create a new entity when I am calling the /entity/entity_type_name endpoint with a POST request, giving the following parameter as json:

{
   "type":[{"target_id":"bundle_name"}],
   "field_test_text":[{"value":"test"}]
}

However, this is only working when I have only one entity type in my list of entities; Let's say for example I decide to create a new entity type, then run the same request, I got the following error message:

Drupal\Core\Entity\Exception\AmbiguousEntityClassException: Multiple entity types found for Drupal\eck\Entity\EckEntity

I understand that apparently, now that I have multiple entity types, the Entity API is not able to understand what should be the type of the entity it has to create (which I find pretty weird, considering that I am providing it in the URL under this form /entity/entity_type_name and that there are different routes available for the different types of entities that I have).

I guess I need to pass an extra parameter in my json for Drupal to understand what kind of entity it should create, but what would be this parameter ? I've been trying to look online and in the documentation, but I cannot figure out how to do this.


Solution

  • I had the same problem, and here is how I resolved it:

    1. Enable the HAL module.
    2. Enable hal_json under Accepted request formats in /admin/config/services/rest for that particular resource.

    Then, in your POST request, use headers:

    • Content-Type: application/hal+json
    • X-CSRF-Token: [AUTH SESSION TOKEN]

    And the body of the request being:

    {
      "_links": {
       "type": {
         "href": "http://localhost:8080/rest/type/[ENTITY_TYPE]/[ENTITY_BUNDLE]"
       }
      },
      "title":[
        {"value": "This is a new entity title"}
      ],
      "field_example":[
        {"value": "This is an example of a custom text field value."}
      ]
    }
    

    Drupal is reading the entity type and bundle from the _links.type.href string.

    For example, if your entity type was automobile and your bundle was car, your URL would be "http://localhost:8080/rest/type/automobile/car"