Custom REST API - Not able to get value from post data

Created on 16 April 2020, over 4 years ago
Updated 6 November 2023, 11 months ago

Hi,
I have created a custom REST API module. But I am not able to receive the post values coming after sent from Postman. No value is coming in post function. My code is,

<?php
  
namespace Drupal\studentapi\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;



/**
* Provides a resource to get view modes by entity and bundle.
*
* @RestResource(
*   id = "student_api",
*   label = @Translation("Student rest resource"),
*   serialization_class = "Drupal\node\Entity\Node",
*   uri_paths = {
*     "canonical" = "/student-api",
*     "https://www.drupal.org/link-relations/create" = "/student-api"
*   }
* )
*/


class StudentRestResource extends ResourceBase{

/**
* A current user instance.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/

/**
* Constructs a Drupal\rest\Plugin\ResourceBase object.
*
* @param array $configuration
*   A configuration array containing information about the plugin instance.
* @param string $plugin_id
*   The plugin_id for the plugin instance.
* @param mixed $plugin_definition
*   The plugin implementation definition.
* @param array $serializer_formats
*   The available serialization formats.
* @param \Psr\Log\LoggerInterface $logger
*   A logger instance.
* @param \Drupal\Core\Session\AccountProxyInterface $current_user
*   A current user instance.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
array $serializer_formats,
LoggerInterface $logger,
AccountProxyInterface $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->currentUser = $current_user;
}

/**
* {@inheritdoc}
*/

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->getParameter('serializer.formats'),
$container->get('logger.factory')->get('exp_fs'),
$container->get('current_user')
);
}

/**
* Responds to POST requests.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
*   The entity object.
*
* @return \Drupal\rest\ModifiedResourceResponse
*   The HTTP response object.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*   Throws exception expected.
*/
public function post($data) {
print_r($data);
die("this is a test");
// You must to implement the logic of your REST Resource here.
// Use current user after pass authentication to validate access.

return new ResourceResponse("test data");
}
}
?>

Not sure why if I am doing any mistake. Any help or suggestions is appreciated in advance.

Thanks.

💬 Support request
Status

Active

Component

Code

Created by

🇮🇳India koushikuk

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇮🇳India Hetal chavda

    For POST resource :

    you need to add uri_paths like this :

    uri_paths = {
    "create" = "/student-api"
    }

  • 🇮🇳India dharmeshbarot Gujarat

    In your post method, you are trying to access the POST data via the $data parameter. However, to retrieve data from the POST request body, you need to use the Request object. Here's how you can modify your code to access the POST data

    <?php
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpKernel\Exception\HttpException;

    // ...

    /**
    * Responds to POST requests.
    *
    * @param \Symfony\Component\HttpFoundation\Request $request
    * The request object.
    *
    * @return \Drupal\rest\ModifiedResourceResponse
    * The HTTP response object.
    *
    * @throws \Symfony\Component\HttpKernel\Exception\HttpException
    * Throws exception if needed.
    */
    public function post(Request $request) {
    // Retrieve POST data from the request body.
    $data = json_decode($request->getContent(), TRUE);

    if ($data === null) {
    throw new HttpException(400, 'Invalid JSON data in the request body');
    }

    // Now, you can access and work with the $data array.

    // Example: Print the data to the log.
    \Drupal::logger('your_module')->notice('Received POST data: ' . print_r($data, TRUE));

    // Implement your custom logic here.

    // Return a response.
    return new ModifiedResourceResponse('Response data');
    }

Production build 0.71.5 2024