How to POST JSON Data Using Guzzle?

Linda Hamilton
Release: 2024-11-23 04:26:11
Original
156 people have browsed it

How to POST JSON Data Using Guzzle?

POSTing JSON with Guzzle

Question:

How do I correctly send a POST request with JSON data using Guzzle? The code below results in an internal server error response:

$request = $this->client->post(self::URL_REGISTER, [
    'content-type' => 'application/json',
], [json_encode($_POST)]);
Copy after login

Answer:

Using Guzzle version 5 or later, you can send JSON data in a POST request as follows:

use GuzzleHttp\Client;

$client = new Client();

// Use GuzzleHttp\RequestOptions::JSON
$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'],
]);

// or use 'json'
$response = $client->post('url', [
    'json' => ['foo' => 'bar'],
]);
Copy after login

The Guzzle documentation provides more details on JSON request options.

The above is the detailed content of How to POST JSON Data Using Guzzle?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template