I'm confusing about the correct way to send parameter to POST request in Magento 2 API
For example, now I need to send a request body like this:
{
"first_name":"test_first",
"last_name":"test_last"
}
(it's just for example, in real situation, the number of key-value pair may be 20 or even 50)
Now I'm currently doing like this in the method declaration (in Api/NameRepositoryInterface.php, for instance)
/**
* @param string $first_name
* @param string $last_name
* @return boolean
*/
public function createFullName($first_name, $last_name);
This approach is working fine, but what if there are 50 key-value pair in the request?
So I have to search for another approach, and it's here:
Now I can define Api/Data/NameInterface.php class like this
interface NameInterface
{
const FIRST_NAME = 'first_name';
const LAST_NAME = 'last_name';
/**
* @return string|null
*/
public function getFirstName();
/**
* @param string $firstName
* @return $this
*/
public function setFirstName($firstName);
/**
* @return string|null
*/
public function getLastName();
/**
* @param string $lastName
* @return $this
*/
public function setLastName($lastName);
}
And in in Api/NameRepositoryInterface.php class, I can make it like this:
/**
* @param \Vendor\Module\Api\Data\NameInterface $name
* @return boolean
*/
public function createFullName(\Vendor\Module\Api\Data\NameInterface $name);
It works well if in every request to this api, I always send both the first_name and last_name
The situation that I want to ask is:
What if in the request I only want to send the first_name as parameter (in real situation, it maybe 30/50 total key-value of NameInterface class)
How can we handle that case?
Do we have to create a new class called Api/Data/NameRequestInterface.php and copy again 30 fields?
I think there must be some better way for this situation, prevent us from repeating our code
Anyone has idea?
Thank you.
Best Answer
you can simply send array as json. Here is example..
Send request: