Roberto Meléndez
Roberto Meléndez

Reputation: 31

Laravel 8 HTTP Client - How to send a string in a POST request

I need to send a POST request to an API that requires a String as a parameter. I'm using Laravel's HTTP Client to make the requests, but the data format is an array.

$response = Http::acceptJson()->withHeaders([
                'Connection' => 'keep-alive',
                'Content-Type' => 'application/json'
            ])->post($url, [ "NtpcFQj9lQQoWuztFpssFoSQTAwbGReBbl6nc4HKYLEm" ]);

This is the post() function from Illuminate\Http\Client\PendingRequest

/**
     * Issue a POST request to the given URL.
     *
     * @param  string  $url
     * @param  array  $data
     * @return \Illuminate\Http\Client\Response
     */
    public function post(string $url, array $data = [])
    {
        return $this->send('POST', $url, [
            $this->bodyFormat => $data,
        ]);
    }

The format I get from the request with a Http::dd()

^ Illuminate\Http\Client\Request {#1381 ▼
  #request: GuzzleHttp\Psr7\Request {#1378 ▼
    -method: "POST"
    -requestTarget: null
    -uri: GuzzleHttp\Psr7\Uri {#1366 ▶}
    -headers: array:6 [▼
      "Content-Length" => array:1 [▶]
      "User-Agent" => array:1 [▶]
      "Host" => array:1 [▶]
      "Accept" => array:1 [▼
        0 => "application/json"
      ]
      "Connection" => array:1 [▼
        0 => "keep-alive"
      ]
      "Content-Type" => array:1 [▼
        0 => "application/json"
      ]
    ]
    -headerNames: array:6 [▶]
    -protocol: "1.1"
    -stream: GuzzleHttp\Psr7\Stream {#1369 ▶}
  }
  #data: array:1 [▼
    0 => "NtpcFQj9lQQoWuztFpssFoSQTAwbGReBbl6nc4HKYLEm"
  ]
}

What I need is that the data has the following format:

^ Illuminate\Http\Client\Request {#1381 ▼
  #request: GuzzleHttp\Psr7\Request {#1378 ▼
    -method: "POST"
    -requestTarget: null
    -uri: GuzzleHttp\Psr7\Uri {#1366 ▶}
    -headers: array:6 [▼
      "Content-Length" => array:1 [▶]
      "User-Agent" => array:1 [▶]
      "Host" => array:1 [▶]
      "Accept" => array:1 [▼
        0 => "application/json"
      ]
      "Connection" => array:1 [▼
        0 => "keep-alive"
      ]
      "Content-Type" => array:1 [▼
        0 => "application/json"
      ]
    ]
    -headerNames: array:6 [▶]
    -protocol: "1.1"
    -stream: GuzzleHttp\Psr7\Stream {#1369 ▶}
  }
  #data: "NtpcFQj9lQQoWuztFpssFoSQTAwbGReBbl6nc4HKYLEm"
  ]
}

Try changing the content-type to "text/plain", but the string is always kept inside the array.

Any solution to send only a string inside the data with HTTP Client? Another PHP library that I can use to make POST requests with a parameter of type string?

Upvotes: 2

Views: 4688

Answers (1)

Petr Gürth
Petr Gürth

Reputation: 67

You can use withBody method

see docs https://laravel.com/docs/9.x/http-client#sending-a-raw-request-body

Upvotes: 1

Related Questions