wordpress: wp_remote_post can't pass body to the fast api, while from api docs and python requests no issue, error msg: value is not a valid dict, 422

Question:

background: I am trying to make a fastapi and wordpress plugin which will use api in localhost (both sits on the same server), i have developed the api and its working perfectly fine through swagger ui and python request library however can’t use it in the plugin through wp_remote_post

code for the api:

from fastapi import FastAPI
from pydantic import BaseModel
from api.article import add_article, html_format_data

app = FastAPI()

class PostData(BaseModel):
    links: list
    title: str

@app.post('/create_post/')
def create_post(post_data: PostData):
    html_format = html_format_data(post_data.links, post_data.title)  # list of dicts
    if add_article(post_data.title, html_format):
        return {"status": 201, "success": True}
    else:
        return {"error"}

python request code:

import requests

data = {
    "title": "gaming",
    "links": [
        {
            "id": "video id 1",
            "thumbnail": "url of thumbnail 1,
            "title": "title of video 1"
        },
        {
            "id": "video id 2",
            "thumbnail": "url of thumbnail 2 ,
            "title": "title of video 2"
        }
    ]
  }
res = requests.post('http://127.0.0.1:5000/create_post/', json=data)
print(res.content)

same success through swagger ui:

curl -X 'POST' 
  'http://127.0.0.1:5000/create_post/' 
  -H 'accept: application/json' 
  -H 'Content-Type: application/json' 
  -d '{
  "links": [
  {
    "id": "shortand",
    "thumbnail": "shortand",
    "title": "shortand"
  },
  {
    "id": "shortand",
    "thumbnail": "shortand",
    "title": "shortand"
  }
],
  "title": "gaming"
}'

but when i do it through wordpress plugin which code is below:

function create_post( $data, $query ) {
    $url = 'http://127.0.0.1:5000/create_post/';
    
    $arguments = array(
        'method' => 'POST',
        'body' => json_encode(array(
                "links" => $data,
                "title" => $query
                )),
        'header' => array(
            'Content-Type' => 'application/json',
            'accept' => 'application/json'
            )
        );
    
    $response = wp_remote_post( $url, $arguments );
//  echo '<script>console.log(`data: ' . $arguments["body"] . '`)</script>';
    echo '<script>console.log(`' . json_encode($response) . '`)</script>';
}

i get this error in the console:

{"headers":{},"body":"{"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}","response":{"code":422,"message":"Unprocessable Entity"},"cookies":[],"filename":null,"http_response":{"data":null,"headers":null,"status":null}}

i am new to wordpress and php.
i did consult these solutions but nothing seem to work as i am doing in from php.

POST request response 422 error {'detail': [{'loc': ['body'], 'msg': 'value is not a valid dict', 'type': 'type_error.dict'}]}

FastAPI – "msg": "value is not a valid dict" in schema request

EDIT
i did the below as suggested BUT still getting the same error, heres the php code:

function create_post( $data, $query ) {
    $url = 'http://127.0.0.1:5000/create_post/';
    $data_arr = array("links" => $data,"title" => $query);
    $data_obj = (object) $data_arr;
    
    $body = json_encode( $data_obj );

    $arguments = array(
        'method' => 'POST',
        'body' => $body,
        'header' => array(
            'Content-Type' => 'application/json',
            'accept' => 'application/json'
            )
        );
    
    $response = wp_remote_post( $url, $arguments );
    echo '<script>console.log(`' . $body . '`)</script>';
    echo '<script>console.log(`' . json_encode($response) . '`)</script>';
}

SOLVED
lol my issue was a idiotic, i missed the "s" in headers so it want any json anymore because it cant see headers so it couldnt find it json thats why it was giving the error not a valid dict.

Asked By: SAVEPALASTINE

||

Answers:

When handling JSON from php, we sometimes run into problems with the distinction between objects and associative arrays.

Try casting your body array as an object before giving it to json_encode(), something like this:

    $body = json_encode( (object)
               array(
                "links" => $data,
                "title" => $query
               ));
    print_r ($body);  //debugging: examine JSON to pass to web service
    $arguments = array(
        'method' => 'POST',
        'body'   => $body,
        'header' => array(
            'Content-Type' => 'application/json',
            'accept' => 'application/json'
            )
        );
    
    $response = wp_remote_post( $url, $arguments );
Answered By: O. Jones
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.