A
A
Abubakr2020-08-24 09:05:38
PHP
Abubakr, 2020-08-24 09:05:38

How to send array in guzzle request?

There is a route that accepts a request like this

type SomeRequest struct {
  amount  float64    `json:"amount"`
  number  string     `json:"number"`
  id      int64      `json:"id"`
  numbers []string   `json:"numbers"`
}

I send a request like this
$response = $guzzle->post('',[
     'headers' => [
         'Accept'      => 'application/json',
         'ApiKeyAuth'  => ...,
     ],
     'json' => [
         "amount"  => $amount,
         "number"  => $number,
         "id"      => (int) id,
         "numbers" => (array)$numbers,
     ],
]);


I get an error
json: 
cannot unmarshal object into Go struct field SomeRequest.numbers of type []string


This is due to the fact that when sending a request using json, all nested arrays are also converted to strings.

The question is, how can you send an array inside the request so that the type remains as it is?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Ommonik, 2020-08-24
@Ommonick

it often helps to take a curl request (for example, generate it from postman) and see what kind of data is in it
if numbers is an array of strings, then you need to specify in the
number string structure `json:"number,string"`
like here
https://stackoverflow.com /questions/35674730/marsh...
(only in the answer and not in the question)
UPD. I overlooked, you have nested structures there so that it can be parsed normally - there should be two structures
, the request structure containing the numbers array
and
the numbers structure containing the number array of type string
type SomeRequest struct {
amount float64 `json:"amount"`
id int64 `json: "id"`
numbers []Numbers `json:"numbers,array"` //not sure about json notation here
}
type Numbers struct {
number string `json:"number,string"`
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question