Giter Club home page Giter Club logo

notion-sdk-php's Introduction

brd6/notion-sdk-php

Notion SDK for PHP

Source Code Download Package PHP Programming Language Read License Build Status

PHP version of the official NOTION API. It works the same way as the reference JavaScript SDK ๐ŸŽ‰

Installation

Install this package as a dependency using Composer.

composer require brd6/notion-sdk-php

This package (brd6/notion-sdk-php) is not tied to any specific library such as Guzzle or Buzz that sends HTTP messages. Instead, it uses the PSR-18 client abstraction to let users choose whichever PSR-7 implementation and HTTP client they want to use.

If you just want to get started quickly with symfony http client, run the following command:

composer require brd6/notion-sdk-php symfony/http-client nyholm/psr7

Usage

Use Notion's Getting Started Guide to get set up to use Notion's API.

Import and initialize a client using an integration token or an OAuth access token.

use Brd6\NotionSdkPhp\Client;
use Brd6\NotionSdkPhp\ClientOptions;

$options = (new ClientOptions())
    ->setAuth(getenv('NOTION_TOKEN'));

$notion = new Client($options);

Make a request to any Notion API endpoint.

See the complete list of endpoints in the API reference.

$listUsersResponse = $notion->users()->list();
var_dump($listUsersResponse->toArray());
array (size=4)
  'has_more' => boolean false
  'results' =>
    array (size=2)
      0 =>
        array (size=6)
          'object' => string 'user' (length=4)
          'id' => string '7f03dda0-a132-49d7-b8b2-29c9ed1b1f0e' (length=36)
          'type' => string 'person' (length=6)
          'name' => string 'John Doe' (length=8)
          'avatar_url' => string 'https://s3-us-west-2.amazonaws.com/public.notion-static.com/521dfe9c-f821-4de8-a0bb-e40ff71283e5/39989484_10217003981481443_4621803518267752448_n.jpg' (length=149)
          'person' =>
            array (size=1)
              ...
      1 =>
        array (size=5)
          'object' => string 'user' (length=4)
          'id' => string '8dee9e49-7369-4a6d-a11f-7db625b2448c' (length=36)
          'type' => string 'bot' (length=3)
          'name' => string 'MyBot' (length=5)
          'bot' =>
            array (size=1)
              ...
  'object' => string 'list' (length=4)
  'type' => string 'user' (length=4)

Endpoint parameters are grouped into a single object. You don't need to remember which parameters go in the path, query, or body.

$databaseRequest = new DatabaseRequest();
$databaseRequest->setFilter([
    'property' => 'Landmark',
    'text' => [
        'contains' => 'Bridge',
    ],
]);
$myPage = $notion->databases()->query('897e5a76-ae52-4b48-9fdf-e71f5945d1af', $databaseRequest)

Handling errors

If the API returns an unsuccessful response, an ApiResponseException will be thrown.

The error contains properties from the response, and the most helpful is code. You can compare code to the values in the NotionErrorCodeConstant object to avoid misspelling error codes.

Client options

The Client supports the following options on initialization. These options can be set on the ClientOptions instance.

Option Default value Type Description
auth '' string Bearer token for authentication. If left undefined, the auth parameter should be set on each request.
timeout 60 number Number of seconds to wait before throw a RequestTimeoutException
baseUrl "https://api.notion.com" string The root URL for sending API requests. This can be changed to test with a mock server.
httpClient Default Http Client Psr\Http\Client\ClientInterface The Http Client used to make request on the Notion API. This can be change to customize the base Http Client or replace with a mocked Http Client.

Contributing

Contributions are welcome! To contribute, please familiarize yourself with CONTRIBUTING.md.

License

The MIT License (MIT). Please see LICENSE for more information.

notion-sdk-php's People

Contributors

brd6 avatar dependabot[bot] avatar misterduval avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

notion-sdk-php's Issues

Can you explain how can we use a create() method?

Can you provide some examples of how to use the create / update methods when using Resources?

I had a hard time understanding how can you build fromRawData resources and I cannot find an example.

Thank you very much.

Database query fails when database includes "select" or "multi-select" columns.

Description

Hi, I've recently encountered an issue where my database queries have started failing for databases including "select" or "multi-select" fields.

Steps to reproduce

  1. Create a notion database that includes a "Select" or "Multi-select" field.
  2. Run database query on the database. e.g $notion->databases()->query('xxxxxxxxxxxxxxxxxxx', $databaseRequest)->getResults();

Expected behavior

A normal response containing my database query results.

Screenshots or output

Here is the error message I receive. If the database contains a "multi-select" field instead, it replaces the field type, but otherwise returns the same error.

development.ERROR: The given property type "select" is unsupported for "value". {"exception":"[object] (Brd6\\NotionSdkPhp\\Exception\\UnsupportedPropertyTypeException(code: 0): The given property type \"select\" is unsupported for \"value\". at /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Property/Value/AbstractValueProperty.php:68)
[stacktrace]
#0 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Property/Value/AbstractValueProperty.php(37): Brd6\\NotionSdkPhp\\Resource\\Property\\Value\\AbstractValueProperty::getMapClassFromType('select')
#1 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Property/Value/ArrayValueProperty.php(26): Brd6\\NotionSdkPhp\\Resource\\Property\\Value\\AbstractValueProperty::fromRawData(Array)
#2 [internal function]: Brd6\\NotionSdkPhp\\Resource\\Property\\Value\\ArrayValueProperty->Brd6\\NotionSdkPhp\\Resource\\Property\\Value\\{closure}(Array)
#3 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Property/Value/ArrayValueProperty.php(27): array_map(Object(Closure), Array)
#4 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Property/Value/AbstractValueProperty.php(44): Brd6\\NotionSdkPhp\\Resource\\Property\\Value\\ArrayValueProperty->initialize()
#5 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Page/PropertyValue/RollupPropertyValue.php(22): Brd6\\NotionSdkPhp\\Resource\\Property\\Value\\AbstractValueProperty::fromRawData(Array)
#6 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Page/PropertyValue/AbstractPropertyValue.php(43): Brd6\\NotionSdkPhp\\Resource\\Page\\PropertyValue\\RollupPropertyValue->initialize()
#7 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Page.php(81): Brd6\\NotionSdkPhp\\Resource\\Page\\PropertyValue\\AbstractPropertyValue::fromRawData(Array)
#8 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/AbstractResource.php(40): Brd6\\NotionSdkPhp\\Resource\\Page->initialize()
#9 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Pagination/PageOrDatabaseResults.php(25): Brd6\\NotionSdkPhp\\Resource\\AbstractResource::fromRawData(Array)
#10 [internal function]: Brd6\\NotionSdkPhp\\Resource\\Pagination\\PageOrDatabaseResults->Brd6\\NotionSdkPhp\\Resource\\Pagination\\{closure}(Array)
#11 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Pagination/PageOrDatabaseResults.php(26): array_map(Object(Closure), Array)
#12 /var/www/html/vendor/brd6/notion-sdk-php/src/Resource/Pagination/AbstractPaginationResults.php(43): Brd6\\NotionSdkPhp\\Resource\\Pagination\\PageOrDatabaseResults->initialize()
#13 /var/www/html/vendor/brd6/notion-sdk-php/src/Endpoint/DatabasesEndpoint.php(54): Brd6\\NotionSdkPhp\\Resource\\Pagination\\AbstractPaginationResults::fromRawData(Array)
#14 /var/www/html/app/Commands/NotionClients.php(44): Brd6\\NotionSdkPhp\\Endpoint\\DatabasesEndpoint->query('fb753c69cf9549a...', Object(Brd6\\NotionSdkPhp\\Resource\\Database\\DatabaseRequest))
#15 /var/www/html/vendor/illuminate/container/BoundMethod.php(36): App\\Commands\\NotionClients->handle()
#16 /var/www/html/vendor/illuminate/container/Util.php(40): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#17 /var/www/html/vendor/illuminate/container/BoundMethod.php(93): Illuminate\\Container\\Util::unwrapIfClosure(Object(Closure))
#18 /var/www/html/vendor/illuminate/container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(LaravelZero\\Framework\\Application), Array, Object(Closure))
#19 /var/www/html/vendor/illuminate/container/Container.php(653): Illuminate\\Container\\BoundMethod::call(Object(LaravelZero\\Framework\\Application), Array, Array, NULL)
#20 /var/www/html/vendor/illuminate/console/Command.php(136): Illuminate\\Container\\Container->call(Array)
#21 /var/www/html/vendor/symfony/console/Command/Command.php(298): Illuminate\\Console\\Command->execute(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))
#22 /var/www/html/vendor/illuminate/console/Command.php(121): Symfony\\Component\\Console\\Command\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))
#23 /var/www/html/vendor/symfony/console/Application.php(1040): Illuminate\\Console\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#24 /var/www/html/vendor/symfony/console/Application.php(301): Symfony\\Component\\Console\\Application->doRunCommand(Object(App\\Commands\\NotionClients), Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#25 /var/www/html/vendor/symfony/console/Application.php(171): Symfony\\Component\\Console\\Application->doRun(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#26 /var/www/html/vendor/illuminate/console/Application.php(94): Symfony\\Component\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#27 /var/www/html/vendor/laravel-zero/foundation/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#28 /var/www/html/vendor/laravel-zero/framework/src/Kernel.php(91): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#29 /var/www/html/silo(37): LaravelZero\\Framework\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#30 {main}
"}

   Brd6\NotionSdkPhp\Exception\UnsupportedPropertyTypeException

  The given property type "select" is unsupported for "value".

  at vendor/brd6/notion-sdk-php/src/Resource/Property/Value/AbstractValueProperty.php:68
     64โ–•         $typeFormatted = StringHelper::snakeCaseToCamelCase($type);
     65โ–•         $class = "Brd6\\NotionSdkPhp\\Resource\\Property\\Value\\{$typeFormatted}ValueProperty";
     66โ–•
     67โ–•         if (!class_exists($class)) {
  โžœ  68โ–•             throw new UnsupportedPropertyTypeException($type, self::PROPERTY_BASE_TYPE);
     69โ–•         }
     70โ–•
     71โ–•         return $class;
     72โ–•     }

      +2 vendor frames
  3   [internal]:0
      Brd6\NotionSdkPhp\Resource\Property\Value\ArrayValueProperty::Brd6\NotionSdkPhp\Resource\Property\Value\{closure}(["select"])

      +7 vendor frames
  11  [internal]:0
      Brd6\NotionSdkPhp\Resource\Pagination\PageOrDatabaseResults::Brd6\NotionSdkPhp\Resource\Pagination\{closure}()

Environment details

  • version of this package: started with 1.1.8, later upgraded to 1.2.1 to no avail.
  • PHP version: 8.1.27
  • OS: Both Ubuntu 20.04.4 LTS (Focal Fossa) and Debian GNU/Linux 12 (bookworm)

Additional context

These errors seem to have started without any changes to my project. Also, other queries seem to work fine for me as long as they do not include a "select" or "multi-select" field.

Thanks for your time! :)

Why does getNumber() cast to an int?

Description

When setting data in Notion in a number field, I'm setting values like 13.75 and 4.25. When I look at the getProperties() in the debugger and see raw data I see my decimal value. But when I then call getNumber() it's casting to an int everywhere.

Steps to reproduce

  1. Create a Notion DB with a number column.
  2. Set a value in the number column that has a decimal.
  3. call ->getProperties() on the row.
  4. call ->getNumber() on the $properties['My number'] it seems to floor() the number.

Expected behavior

I would expect the value as a decimal.

Screenshots or output

https://github.com/brd6/notion-sdk-php/blob/main/src/Resource/Property/Value/NumberValueProperty.php

Environment details

PHP 8.1 in DDEV.

Creating an empty list item or todo

See the title. I want to create come empty list items and todos, like you can make in the app itself and in many templates. but api is rejecting it

How do I... ?

This is the response I'm getting from the API
Client error: `POST https://api.notion.com/v1/pages/` resulted in a `400 Bad Request` response: {"object":"error","status":400,"code":"validation_error","message":"body failed validation. Fix one:\nbody.children[7].b (truncated...)

Example code

Its happens when I add a bulleted list items like this

        $block = new BulletedListItemBlock();
        $blockProperty = new BulletedListItemProperty();
        $blockProperty->setRichText([Text::fromContent("")]);
        $block->setBulletedListItem($blockProperty);
        ...

Status Property error

Hello, i'm quite new to Notion API. I tried to query a database in order to get one ticket depends on a property number. But after adding filter and query I get a message : The given property value "status" is unsupported.
I think that come from there is no StatusProperty class but i'm not sure. WDYT ?
Things is, if i dump the rawdata from tue query method, it works.

Here is my code from my controller : 
    $databaseRequest = new DatabaseRequest();
    $databaseRequest->setFilter([
        'property' => 'PlusID',
        'number' => [
            'equals' => 2,
        ],
    ]);
    $myPage = $notion->databases()->query('####', $databaseRequest);
    dump($myPage); die;

Thanks

setFilter() throws ApiResponseException

I am performing a very simple database query. I am able to run it just fine without passing any filters, but when I try to pass set_cursor through to get the next batch of pages, it throws this error:

Fatal error: Uncaught Brd6\NotionSdkPhp\Exception\ApiResponseException: body failed validation. Fix one:
body.filter.or should be defined, instead was undefined.
body.filter.and should be defined, instead was undefined.
body.filter.title should be defined, instead was undefined.
body.filter.rich_text should be defined, instead was undefined.
body.filter.number should be defined, instead was undefined.
body.filter.checkbox should be defined, instead was undefined.
body.filter.select should be defined, instead was undefined.
body.filter.multi_select should be defined, instead was undefined.
body.filter.status should be defined, instead was undefined.
body.filter.date should be defined, instead was undefined.
body.filter.people should be defined, instead was undefined.
body.filter.files should be defined, instead was undefined.
body.filter.url should be defined, instead was undefined.
body.filter.email should be defined, instead was undefined.
body.filter.phone_number should be defined, instead was undefined.
body.filter.relation should be defined, instead was undefined.
body.filter.created_by should be defined, instead was undefined.
body.filter.created_time should be defined, instead was undefined.
body.filter.last_edited_by should be defined, instead was undefined.
body.filter.last_edited_time should be defined, instead was undefined.
body.filter.formula should be defined, instead was undefined.
body.filter.rollup should be defined, instead was undefined.

This is the part of my code I'm running. It throws the exception in the second iteration when it passes through set_cursor.

$foodItemsArray = array();
$hasMore = true;
$nextCursor = "";
$i = 0;
while($hasMore) {
echo $i++;
$databaseRequest = new DatabaseRequest();
if($nextCursor != "") $databaseRequest->setFilter(['start_cursor' => $nextCursor]);
$foodItemsRequest = $notion->databases()->query($foodItemsDBID, $databaseRequest);
$currArray = $foodItemsRequest->toArray();
$hasMore = $currArray["has_more"];
$nextCursor = $currArray["next_cursor"];
$foodItemsArray = array_merge($foodItemsArray, $currArray["results"]);
}

I'm quite new to using the Notion API so I feel like there must be something very simple here I'm just missing!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.