Problem/Motivation

Discovered while working on #2930028: Comprehensive JSON API integration test coverage phase 1: for every entity type, individual resources only.

Sending a bodyless POST or PATCH request results in

1) Drupal\Tests\jsonapi\Functional\NodeTest::testPatchIndividual
Exception: TypeError: Argument 2 passed to Drupal\jsonapi\Controller\EntityResource::patchIndividual() must implement interface Drupal\Core\Entity\EntityInterface, instance of Symfony\Component\HttpFoundation\Request given
Drupal\jsonapi\Controller\EntityResource->patchIndividual()() (Line: 242)
…
2) ) Drupal\Tests\jsonapi\Functional\NodeTest::testPostIndividual
Exception: TypeError: Argument 1 passed to Drupal\jsonapi\Controller\EntityResource::createIndividual() must implement interface Drupal\Core\Entity\EntityInterface, instance of Symfony\Component\HttpFoundation\Request given
Drupal\jsonapi\Controller\EntityResource->createIndividual()() (Line: 193)

Proposed resolution

Fix \Drupal\jsonapi\Controller\RequestHandler::handle().

Remaining tasks

TBD

User interface changes

None.

API changes

None.

Data model changes

None.

Comments

Wim Leers created an issue. See original summary.

wim leers’s picture

Status: Active » Needs review
StatusFileSize
new3.41 KB

Now that #2883086: [PP-1] Port RequestHandler + ResourceResponseSubscriber improvements from REST module to JSON API is done, it's much easier to move this forward!

And in fact, the two places where this issue was cited and test assertions were commented both covered too much ground. Both included test assertions that #2934149: [>=8.5] JSON API routes not specifying _content_type_format route requirement, resulting in bad DX will uncomment. So, selectively uncommenting and updating the @todos.

Note that core REST does this check in \Drupal\rest\Plugin\rest\resource\EntityResource::patch() and \Drupal\rest\Plugin\rest\resource\EntityResource::post(). But JSON API can be smarter about it: do it in \Drupal\jsonapi\Controller\RequestHandler::handle()!

e0ipso’s picture

Status: Needs review » Needs work
+++ b/src/Controller/RequestHandler.php
@@ -112,6 +112,9 @@ class RequestHandler {
+    if ($unserialized === NULL && ($request->isMethod('POST') || $request->isMethod('PATCH'))) {

https://httpstatuses.com/422

If the unserialized entity is NULL because of a missing body, 400 is OK. If it's NULL because the body is not valid JSON or not valid application/vnd.api+json, then 415. If it's NULL because it contains valid application/vnd.api+json but an entity could not be built with it, we need a 422.

wim leers’s picture

Status: Needs work » Needs review
StatusFileSize
new1.54 KB
new3.75 KB

If the unserialized entity is NULL because of a missing body, 400 is OK. If it's NULL because the body is not valid JSON or not valid application/vnd.api+json, then 415. If it's NULL because it contains valid application/vnd.api+json but an entity could not be built with it, we need a 422.

Yes, and those cases are handled by \Drupal\jsonapi\Controller\RequestHandler::deserialize() since #2883086: [PP-1] Port RequestHandler + ResourceResponseSubscriber improvements from REST module to JSON API:

  • Non-decodable (invalid) JSON already throws a 400 (since #2883086 — this is one of the key bugfixes in there).
  • Decodable (valid) JSON but not denormalizable (invalid JSON API normalization) already throws a 422 (since before #2883086).

I totally agree that it's not very clear though. So, moving that new if-test into ::deserializeBody() which I think makes this 10x more clear :)

gabesullice’s picture

Status: Needs review » Needs work
+++ b/src/Controller/RequestHandler.php
@@ -201,6 +202,10 @@ class RequestHandler {
+      throw new BadRequestHttpException('No entity content received.');

Nit: "Empty request body"

Let's avoid Drupal terms (although technically you could say they're not :P )

RTBC if nit is addressed.

wim leers’s picture

Status: Needs work » Reviewed & tested by the community
StatusFileSize
new1.67 KB
new3.9 KB

👌 (I c/p'ed that from \Drupal\rest\Plugin\rest\resource\EntityResource::post().)

  • Wim Leers committed 6a37edb on 8.x-1.x
    Issue #2943170 by Wim Leers, e0ipso, gabesullice: JSON API's...
  • Wim Leers committed 02f0a8d on 8.x-2.x
    Issue #2943170 by Wim Leers, e0ipso, gabesullice: JSON API's...
wim leers’s picture

Status: Reviewed & tested by the community » Fixed

Green test run! Also: yay, again more of the test coverage ported from core REST is actually running!

pwolanin’s picture

I just updated to 8.x-1.17 and I am still getting similar errors when running our behat tests. In the test a node is unpublished via PATCH and then the user tries to fetch it with GET.

The error is not happening with a simple GET when I do it manually

The error message is the same as in the issue description here:

    And the request body is:                                                                                  
      """
      {
      "data": {
      "id" : "719858ee-c0b6-4251-88f5-0bacbda3201c",
      "type": "node--chemical_container",
      "attributes": {
      "status": 0
      }
      }
      }
      """
    When I request "/jsonapi/node/chemical_container/719858ee-c0b6-4251-88f5-0bacbda3201c" using HTTP "PATCH" 
    Then the response code is 200                                                                             
    When I request "/jsonapi/node/chemical_container/719858ee-c0b6-4251-88f5-0bacbda3201c" using HTTP "GET"   
    Then the response code is 403                                                                             
      Expected response code 403, got 500. (Imbo\BehatApiExtension\Exception\AssertionFailedException)
    │  
    │
    └─ @AfterStep # Devinci\DevinciExtension\Context\DebugContext::dumpAssetsAfterFailedStep()

  │
  │  stdClass Object
  │  (
  │      [wid] => 157470
  │      [uid] => 999999999
  │      [type] => php
  │      [message] => %type: @message in %function (line %line of %file) @backtrace_string.
  │      [variables] => Array
  │          (
  │              [%type] => TypeError
  │              [@message] => Argument 2 passed to Drupal\jsonapi\Controller\EntityResource::getIndividual() must be an instance of Symfony\Component\HttpFoundation\Request, instance of Drupal\node\Entity\Node given
  │              [%function] => Drupal\jsonapi\Controller\EntityResource->getIndividual()
  │              [%file] => /Users/pwolanin/bioraft/bioraft4/web/modules/drupal/jsonapi/src/Controller/EntityResource.php
  │              [%line] => 125
  │              [@backtrace_string] => #0 [internal function]: Drupal\jsonapi\Controller\EntityResource->getIndividual(Object(Drupal\node\Entity\Node), Object(Drupal\node\Entity\Node), Object(Symfony\Component\HttpFoundation\Request))
pwolanin’s picture

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.