0

I'm trying to create a node via Drupal API but I get this error:

Got error 'PHP message: PHP Fatal error:  Uncaught GuzzleHttp\\Exception\\ClientException: Client error: `POST https://site.it/entity/node?_format=hal_json` resulted in a `422 Unprocessable Entity` response:\n{"message":"Could not determine entity type bundle: \\u0022type\\u0022 field is missing."}

This is my function:

public function createFaq($notes, $telegram_id){
  $url = "/entity/node?_format=hal_json"; 
  $opt = [
    'headers' => self::$baseHeader,
    'body' => json_encode([
      [
        'type' => [ ['target_id' => 'faq'] ],
        'title' => 'title', 
        'utente' => [ [ 'target_id' => '123462' ] ],
        'field_domanda' => [ [ 'value' => $notes['domanda'] ] ],
        'field_presenza' => [ [ 'value' => $notes['presenza'] == "Si"? true : false ] ],
      ]
    ])
  ];

  $response = $this->client->request('POST', $url , $opt);
  $r = json_decode( $response->getBody());
  return $r; 
}

But it's really strange, because this other function is working:

public static function createUser($title){
  $url= "/entity/node?_format=hal_json"; 
  $opt = [
    'headers' => self::$baseHeader,
    'body' => json_encode([
      'title' => [ [ 'value' => $title ] ],
      'type' => [ [ 'target_id' => 'article' ] ],
    ])
  ];

  $response = $this->client->request('POST', $url , $opt);
  $r = json_decode( $response->getBody());
  return $r; 
}

Can someone understood my error?

2
  • 3
    Your second (working) example has this POST body ['type' => ...] whereas the first example has it wrapped in an additional array: [['type' => ...]].
    – berliner
    Commented Jan 10, 2022 at 22:44
  • You are right!! Thank you <3
    – Shyghar
    Commented Jan 11, 2022 at 10:04

1 Answer 1

0

This is the code I used to create a node using rest api:

Endpoint: /node?_format=hal_json

Method: POST

Body:

{
  "title": [
    {
      "value": "This is a question"
    }
  ],
  "field_question": [
    {
      "value": "This is the question"
    }
  ],
  "field_options": [
    {
      "value": "This is the right option"
    },
    {
      "value": "This is not the right option"
    },
    {
      "value": "This is defenitely not the right option"
    },
    {
      "value": "This is the most silly option"
    }
  ],
  "type": [
    {
      "target_id": "question"
    }
  ]
}

Enable the Rest UI module to check if the endpoint exists. Actually I can't find the plugin proposing this endpoint but having Rest UI enabled I saw this URI for posting content types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.