Indranil
Indranil

Reputation: 2743

How to pass string in post request body in postman

I have an POST API end point, i.e.

[Route("api/{parameter1}/employee")]
[HttpPost]
public Employee RegisterEmployee(string parameter1, [FromBody] string parameter2)

Now, I want to hit this API from postman.

My request URL is:

http://localhost:xxxxx/api/parameter1/employee

And the body is:

enter image description here

So, in this way I am getting: 415 Unsupported Media Type error.

If I try other ways then i am able to hit the API, but parameter2 is always coming as null.

So, how should I pass the parameter2 value in postman?

Upvotes: 11

Views: 47797

Answers (3)

M. Arnold
M. Arnold

Reputation: 425

You now have to specify where the string/int is coming from. i.e. in your controller method specify: GetUser([FromBody] string username) then in postman ensure your are sending the string as JSON

Upvotes: 0

Sanjay Kumar Das
Sanjay Kumar Das

Reputation: 39

Pass simple String from Postman

<route url="/V1/test/" method="POST">
    <service class="App\CustomRestApi\Api\TestInterface" method="testData"/>
    <resources>
        <resource ref="anonymous" />
    </resources>
</route>

enter image description here

Interface

 namespace App\CustomRestApi\Api;
 interface TestInterface
{
 /**
  * Return request
  *
  * @param string $customData
  * @return mixed
  */
 public function testData(string $customData);}

Model

namespace App\CustomRestApi\Model;
use App\CustomRestApi\Api\TestInterface;
class Test implements TestInterface
{
 /**
  * @param string $customData
  * @return string
  */
 public function testData(string $customData)
 {
    return $customData;
 }
 }

di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 <preference for="App\CustomRestApi\Api\TestInterface"
            type="App\CustomRestApi\Model\Test" />
 </config>

Upvotes: 0

Martin Staufcik
Martin Staufcik

Reputation: 9492

Try setting content type to application/json. JSON String inputs thankfully capture as strings in ASP.NET Core.

enter image description here

Alternatively, you could read the body string from the request stream:

using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{  
    return await reader.ReadToEndAsync();
}

Upvotes: 9

Related Questions