Home > Mobile >  Trying to send Query to Notion API using PHP
Trying to send Query to Notion API using PHP

Time:11-18

I am trying to query a Notion Database using the Notion API and PHP. I am able to connect to the API no problem, however it seems my POST request is being ignored and I just get a swath of data which doesn't help me at all.

Notion's API documentation page for this POST request (https://developers.notion.com/reference/post-database-query#post-database-query-filter) states that the payload should look as follows:

{
  "property": "Landmark",
  "text": {
    "contains": "Bridge"
  }
}

Currently my code for performing the PUT looks like so:

//connection information
$databaseId = "zzz";
$url = "https://api.notion.com/v1/databases/$databaseId/query"; //api endpoint
$token = 'zzx';
$version = '2021-08-16';

//post data
$data_array =
[
  "property"=>"DataElement",
  "title"=>["equals"=>"bigHouse"]
];

$data = json_encode($data_array);

//intialize cURL
$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//below is for posting
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token,
  'Notion-Version: '.$version));

$resp = curl_exec($ch);

if($e = curl_error($ch))
{
    echo $e;
} else
{
    $decoded = json_decode($resp, true);
  var_dump($decoded);
}

//file_put_contents('test.json',json_encode($decoded, JSON_PRETTY_PRINT));

echo "<br>".$data;

curl_close($ch);

?>

I have removed the connection information for security reasons and that's not where the issue lies. I am getting all the JSON data from my POST request, however I'm only trying to get the data that matches my payload. The final bits of code like the echo and var_dump are for testing. If I echo $data, I get:

{"property":"DataElement","title":{"equals":"bigHouse"}}

Which, when formatted is what Notion's API requires. I am trying to search the first column of a Notion Database which is called "DataElement" and is of type "Title"

Any assistance would be very helpful. Thank you!

CodePudding user response:

The filter needs to be in the filter parameter.

$data_array =
['filter' => 
    [
      "property"=>"DataElement",
      "title"=>["equals"=>"bigHouse"]
    ]
];

See https://developers.notion.com/reference/post-database-query

  • Related