I'm trying to fill ACF Fields using Wordpress Rest-Api in Python, but when I try to make request it's giving "400 Bad Request". I'm using ACF latest verison 5.11 that comes with in-built api integration.
This is my code, please help me to solve this problem.
import requests
import json
import base64
url = "example.com/wp-json/wp/v2/posts"
user = "exmaple#gmail.com"
password = "RIHr O7kE SCn0 LXVW xyPc jBn9"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
post = {
"title" : "Hello World",
"type" : "post",
"status" : "publish",
"content" : "This is my first post created using rest API",
"acf" : {
"youtube_url": "https://www.youtube.com/watch?v=0outb6oSJW4"
}
}
responce = requests.post(url , headers=header, json=post)
print(responce.status_code, responce.reason)
Three things to check/change here
In your functions.php file in WordPress, ensure you've registered the post meta. For example
function function_name() {
register_meta('post', 'youtube_url',
[
'object_subtype' => 'post',
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
}
]
);
}
add_action( 'rest_api_init', 'function_name' );
2 then update...
"acf" : {
"youtube_url": "https://www.youtube.com/watch?v=0outb6oSJW4"
}
to...
"meta" : {
"youtube_url": "https://www.youtube.com/watch?v=0outb6oSJW4"
}
3 And finally, in the field group settings in ACF, ensure 'Show in REST API' is selected
Related
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.
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 );
I've been trying to build this stock prediction web app using Prophet model and FastAPI. I'm stuck at this problem where I'm getting console log error: 422 Unprocessable Entity.
Here's the react code to get API request:
async function GetAPI () {
const [predData, setPred] = React.useState();
const [stock_name, setStock] = React.useState();
const axios = require('axios');
var data = JSON.stringify({
"ticker": stock_name
})
try{
let response = await axios({
method: 'post',
url:'http://0.0.0.0:8000/predict',
headers: {
'accept' : 'application/json',
'Content-Type' : 'application/json'
},
data: data
},
)
if (response.status==200){
console.log(response.data);
setPred(response.data);
}
return {predData}
}
catch(error){
console.log(error);
}
}
This is the FastAPI function in my python backend:
#app.post("/predict")
def prediction(payload: StockIn):
stock_name = payload.stock_name
pred = stock_prediction(stock_name)
a = int(pred)
response_object = {"data" : a }
return response_object
Can anyone help me out here?
First of all, you send {'ticker': '...'}.
And in backend you try to access a property called stock_name.
Most likely this is caused by it.
If that doesn't help, check below.
It seems that your situation is related with your backend, so you can edit the header.
You can check the variables by simply adding
print statements after important parts.
For example;
#app.post("/predict")
def prediction(payload: StockIn):
print('Payload:', payload)
stock_name = payload.stock_name
pred = stock_prediction(stock_name)
print('Pred:', pred)
a = int(pred)
response_object = {"data" : a }
return response_object
NOTE: It's about backend because axios doesn't interfere with the response codes.
I have successfully made an alert post using Python, but cannot get my powershell alert creation to work. I just get a wall of HTML in my response and no alert creation. Message is the only required field.
Here's what I'm using and it does not work
$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
$head = #{"Authorization" = "GenieKey $api"}
$body = #{
message = "testing";
responders =
]#{
name = "TEAMNAMEHERE";
type = "team"
}]
} | ConvertTo-Json
$request = Invoke-RestMethod -Uri $URI -Method Post -Headers $head -ContentType "application/json" -Body $body
$request
Here is my python code I made and it works just fine.
import requests
import json
def CreateOpsGenieAlert(api_token):
header = {
"Authorization": "GenieKey " + api_token,
"Content-Type": "application/json"
}
body = json.dumps({"message": "testing",
"responders": [
{
"name": "TEAMNAMEHERE",
"type": "team"
}
]
}
)
try:
response = requests.post("https://api.opsgenie.com/v2/alerts",
headers=header,
data=body)
jsontemp = json.loads(response.text)
print(jsontemp)
if response.status_code == 202:
return response
except:
print('error')
print(response)
CreateOpsGenieAlert(api_token="XXX")
EDIT: So I've figured out it has something to do with my "responders" section. It has something to do with the [ ]...but I haven't been able to figure out what exactly. If I remove them, it wont work. If I turn the first one around, it won't work. I can get the alert to create successfully, however I keep getting the following error:
] : The term ']' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\file\Tech\user\powershell scripts\.not working\OpsGenieAlert.ps1:7 char:17
+ ]#{
+ ~
+ CategoryInfo : ObjectNotFound: (]:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
You need to convert your $body to JSON
$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
# Declare an empty array
$responders = #()
# Add a new item to the array
$responders += #{
name = "TEAMNAMEHERE1"
type = "team1"
}
$responders += #{
name = "TEAMNAMEHERE2"
type = "team2"
}
$body = #{
message = "testing"
responders = $responders
} | ConvertTo-Json
$invokeRestMethodParams = #{
'Headers' = #{
"Authorization" = "GenieKey $api"
}
'Uri' = $URI
'ContentType' = 'application/json'
'Body' = $body
'Method' = 'Post'
}
$request = Invoke-RestMethod #invokeRestMethodParams
I am new in Python and airflow. I want to create a dataproc cluster using an http request inside a pythonoperator task. See the below code:
def create_cluster():
API_ENDPOINT = "https://dataproc.googleapis.com/v1beta2/projects/trim
-**********/regions/us-central1-b/clusters"
data = {
"projectId": "trim-**********",
"clusterName": "cluster-1",
"config": {
"configBucket": "",
"gceClusterConfig": {
"subnetworkUri": "default",
"zoneUri": "us-central1-b"
},
"masterConfig": {
"numInstances": 1,
"machineTypeUri": "n1-standard-1",
"diskConfig": {
"bootDiskSizeGb": 500,
"numLocalSsds": 0
}
},
"workerConfig": {
"numInstances": 2,
"machineTypeUri": "n1-standard-1",
"diskConfig": {
"bootDiskSizeGb": 100,
"numLocalSsds": 0
}
}
}
}
r = requests.post(url=API_ENDPOINT, data=data)
pastebin_url = r.text
print("The pastebin URL is:%s" % pastebin_url)
But I am getting an error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
What would be the solution for this error? Thanks in advance.
What is wrong here?
query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query+'\"}',headers=headers)
print (r2.json())
I've got
{'message': 'Problems parsing JSON', 'documentation_url': 'https://developer.github.com/v3'}
but this snippet of code below works correctly
query1= '''{ viewer { login name } }'''
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query1+'\"}',headers=headers)
print (r2.json())
I've tried out to change quotes (from " into ' or with " and so on) but it doesn't work.
The problem is related with the double quotes (").
On the first snippet, when you join the '{"query": \"'+query+'\"}' with the query variable, you get the following result:
{"query": "{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }"}
Notice how the double quote from "ALEXSSS" are not escaped, therefore the resultant string is not a json valid format.
When you run the second snippet, the resultant string is:
{"query": "{ viewer { login name } }"}
which is a valid json string.
The easiest and best solution is simply use the JSON library instead of trying to do it manually, so you won't need to worry about escaping characters.
import json
query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', json.dumps({"query": query}), headers=headers)
print (r2.json())
But remember that you could also just escape the characters on the query manually:
query='{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": "'+query1+'"}', headers=headers)
print (r2.json())
it works as expected :)