Giter VIP home page Giter VIP logo

pinterest-python-sdk's Introduction

Pinterest SDK for Python

build

Introduction

The Pinterest SDK currently offers a Python library that supports campaign management and simplifies authentication and error handling. We will be adding functionality supporting organic Pins, shopping, analytics, and more over time. If you have specific feedback about the SDK or requests for additional functionality, please let us know.

Pre-requisites

  • Python 3.7+
  • a registered application (see below)
  • an access token (see below)

Register an App

In order to use the SDK, you must have registered an app on developers.pinterest.com

The steps to create an app can be found in the Set up app section of the docs on the Developers' Site.

Get Access Token

Follow the instructions outlined on the Pinterest Developer Platform's Authentication Section to retreive an Access Token and Refresh Token

Install package

NOTE: For Python3, use python3 and pip3 instead.

NOTE: If the commands below result in a permissions error (which may happen if you are using a system-installed Python), use sudo.

To install pip, please refer to pip installation guide.

[Recommended] Create a virtual environment:

# Create environment
$ python -m venv .venv

# Activate environment
$ source .venv/bin/activate

Install SDK:

$ pip install pinterest-api-sdk

Alternatively, you can check out the repository from GitHub. Once the package is downloaded and unzipped, install it:

$ python setup.py install

You can now use the SDK.

Getting Started

For use the client you need set basic variables for that you have two option setup environment variables (using a .env file or set in your OS) or create a config.json.

Setting up environment variables

To configure the client using environment variables, you must create a .env file using .env.example as a template. For basic configuration and usage you need to set the following environment variables in the .env file:

PINTEREST_APP_ID=<app id>
PINTEREST_APP_SECRET=<app secret>
PINTEREST_REFRESH_ACCESS_TOKEN='<refresh token>'

**or**

PINTEREST_ACCESS_TOKEN='<access token>'

Once you have established the environment variables, the client will be instantiated for you automatically.

NOTE:

  • Setting the PINTEREST_ACCESS_TOKEN (which is valid for thirty days) will require the token value to be replaced when it expires. You will need to manually reinsantiate the client when the access_token expires.
  • Setting the PINTEREST_REFRESH_ACCESS_TOKEN (which is valid for a year) will allow the SDK to regenerate the new access token whenever it is required.

Setting up config.json

To configure the client using config.json, you must create a config.json file using config.json.example as a template. For basic configuration and usage you need to set the following key in the config.json file:

{
  "app_id": "<app id>",
  "app_secret": "<app secret>",
  "refresh_access_token": "<refresh token>"
}

or

{
  "access_token": "<access token>"
}

Once you have established the keys, the client will be instantiated for you automatically.

NOTE:

  • Setting up environment variables and config.json will result in the environment variables overriding the keys in config.json
  • Setting the access_token (which is valid for thirty days) will require the token value to be replaced when it expires. You will need to manually reinsantiate the client when the access_token expires.
  • Setting the refresh_access_token (which is valid for a year) will allow the SDK to regenerate the new access token whenever it is required.

For more information visit the Authentication page.

Samples

Initializing Models

Use Case:

  • Initialize a Campaign object using an existing Ad Account ID and Campaign ID.
from pinterest.ads.campaigns import Campaign

campaign = Campaign(
    ad_account_id="123456789",
    campaign_id="987654321",
)

Examples of Campaign Management using SDK

Use Case:

  • Create a new Ad
  • Assign the Ad to an existing Ad Group
  • Activate the Ad Group's parent Campaign
  • Change the Campaign's budget
from pinterest.ads.campaigns import Campaign
from pinterest.ads.ad_groups import AdGroup
from pinterest.ads.ads import Ad

## Create a new Ad
new_ad = Ad.create(
    ad_account_id="123456789",
    ad_group_id="999999999",
    creative_type="REGULAR",
    pin_id="111111111",
    name="SDK Example Ad",
    status="ACTIVE",
    is_pin_deleted=False,
    is_removable=False,
)

## Initialize existing paused Campaign
campaign = Campaign(
    ad_account_id="123456789",
    campaign_id="987654321",
)

## Activate campaign
getattr(campaign, '_status')
>>> 'PAUSED'

campaign.activate()
>>> True

getattr(campaign, '_status')
>>> 'ACTIVE'

## Change campaign's lifetime budget
campaign.set_lifetime_budget(
    new_spend_cap=250000000
)
>>> True

Note: More examples of usage are located in the examples/ folder.

Documentation

Exceptions

See pinterest.utils.sdk_exceptions for a list of exceptions which may be thrown by the SDK.

Debugging

If the SDK is not working as expected there might be an issue with the SDK or the Pinterest API server itself. In order to debug and identify the issue, the environment variables for debugging and logging can be enabled.

PINTEREST_DEBUG = True
PINTEREST_LOG_FILE = /tmp/log.txt
PINTEREST_LOGGER_FORMAT = '%(asctime)s %(levelname)s %(message)s'

When PINTEREST_DEBUG is enabled, all the API raw requests and responses will be printed to the console and to the log file in the requested format.

Issues

For any issues or questions related to the SDK you are welcome to submit them through GitHub Issues using the following templates:

Note: There is no guaranteed SLA for responding to or resolving issues.

For any general issues related to the Pinterest API (or other Pinterest products) you can contact support at help.pinterest.com

Other Resources

Additional information on the Pinterest SDK can be found here. Additional information about campaigns and campaign management can be found in:

Advanced Options

Importing the PinterestSDKClient

In order to access or use the client you can import the PinterestSDKClient and call the create_default_client() classmethod:

from pinterest.client import PinterestSDKClient
default_client = PinterestSDKClient.create_default_client()

This will allow you to use the SDK Models without passing a PinterestSDKClient Object.

Creating custom Pinterest SDK Clients

In order to create an object of the PinterestSDKClient you need to pass the access token inside the python code every time you wish to create a client or a combination of the refresh token, app id and app secret. This option is more useful if you wish to work with multiple accounts or clients at the same time.

from pinterest.client import PinterestSDKClient

# Access Token for Client 1
pinterest_access_token_1 = <access token 1>

# Refresh Token for Client 2
pinterest_refresh_token_2 = <refresh token 2>
pinterest_app_id_2 = <app id 2>
pinterest_app_secret_2 = <app secret 2>

client_1 = PinterestSDKClient.create_client_with_token(
    access_token=pinterest_access_token_1,
)
client_2 = PinterestSDKClient.create_client_with_refresh_token(
    refresh_token=pinterest_access_token_2,
    app_id=pinterest_app_id_2,
    app_secret=pinterest_app_secret_2,
)

License

Pinterest Python SDK is licensed under the LICENSE file in the root directory of this source tree.

pinterest-python-sdk's People

Contributors

ambud avatar dfana01 avatar rushabhvaria avatar senseiseun avatar t20 avatar thucngyyen 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pinterest-python-sdk's Issues

Feature Request - <Issue Title>

What is your feature request? Please describe.

A clear and concise description of what the problem is or what new feature you would like us to add. Ex. I'm always frustrated when [...] or I would like to be able to [...]

Describe the solution you'd like

A clear and concise description of what you want to happen.

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.

Additional context

Add any other context or screenshots about the feature request here.

BUG - SDK Client pin creation fails but endpoint is working

Describe the bug

I'm able to create pins using the python requests package and endpoint provided in the Pinterest API docs but when I try using the SDK I get permissions error.

To Reproduce
Unsuccessful using SDK:

from pinterest.client import PinterestSDKClient
from pinterest.organic.pins import Pin

PinterestSDKClient.set_default_access_token(<token>)

params = {
    "board_id": <board_id>,
    "ad_account_id": <ad_account>,
    "description": <description>,
    "link":  <link>,
    "title": <title>,
    "media_source":{
        'source_type':'image_base64',
        'data': <image>,
        'content_type':"image/png"
    }
Pin.create(**params)

The above returns the following error:

Reason: Not Found
HTTP response headers: HTTPHeaderDict({'Content-Type': 'application/json', 'Content-Length': '38', 'pinterest-version': 'c7fe355', 'x-content-type-options': 'nosniff', 'x-frame-options': 'DENY', 'Access-Control-Allow-Credentials': 'true', 'p3p': 'CP="Pinterest does not have a P3P policy. You can find our privacy policy at https://www.pinterest.com/_/_/policy/privacy-policy."', 'x-envoy-upstream-service-time': '83', 'pinterest-generated-by': 'tpp-api-canary-0a0308c3', 'X-RateLimit-Limit': '100, 100;w=1, 1000;w=60', 'X-RateLimit-Remaining': '99', 'X-RateLimit-Reset': '1', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'x-pinterest-rid': '6639680265060241', 'Date': 'Tue, 14 May 2024 16:13:42 GMT', 'Alt-Svc': 'h3=":443"; ma=600', 'Connection': 'keep-alive', 'Set-Cookie': '_ir=0; Max-Age=1800; HttpOnly; Path=/; Secure', 'AKAMAI-GRN': '0.de6533b8.1715703222.1e8acbde', 'X-CDN': 'akamai'})
HTTP response body: {"code":50,"message":"Pin not found."}

The following python request works

import requests
params = {
    "board_id": <board_id>,
    "ad_account_id": <ad_account>,
    "description": <description>,
    "link":  <link>,
    "title": <title>,
    "media_source":{
        'source_type':'image_base64',
        'data': <image>,
        'content_type':"image/png"
    }
auth = {'Authorization': 'Bearer {}'.format(<token>)}
auth["Content-Type"] = "application/json"
pin = requests.post('https://api.pinterest.com/v5/pins', json=params, headers=self.auth).json()

Screenshot of response using above method:
image

Additional Details:

  • MacOS Sonoma 14.3 M1 chip
  • pinterest-api-sdk==0.2.1

BUG - <Issue Title>

Describe the bug

A clear and concise description of what the bug is.

To Reproduce

Steps to reproduce the behavior:

  1. The model/class with an issue is '....'
  2. The function with an issue is '....'
  3. The arguments passed to the model/function are '....'
  4. The error thrown is '....'

Expected behavior

A clear and concise description of what you expected to happen.

Screenshots

If applicable, add screenshots to help explain your problem.

Additional Details (please complete the following information):

  • OS and Version: [e.g. MacOS, Windows]
  • SDK Version [e.g. v0.1.0]

Additional Context

Add any other context about the problem here.

BUG - Inconsistent usage of client in cls._create method for Audience and CustomerList objects

Hello,

I'm experiencing an issue while using the Python SDK for ads.
I typically instantiate a client using the create_client_with_refresh_token method without relying on config.json or environment variables.
Most methods of the Audience and CustomerList objects work fine using this approach, except for the create method.

The problem arises from the fact that the cls._create method within the create method doesn't utilize the client passed to the Audience object. Instead, it searches for a default client elsewhere. The same issue occurs with the CustomerList object. :

response = cls._create(
            params={
                "ad_account_id": str(ad_account_id),
                "audience_create_request": AudienceCreateRequest(
                    ad_account_id=str(ad_account_id),
                    name=name,
                    rule=rule,
                    audience_type=audience_type,
                    description=description if description else '',
                    **kwargs
                ),
            },
            api=AudiencesApi,
            create_fn=AudiencesApi.audiences_create
        )

My question is whether this behavior is intended. Is it mandatory to use config.json or environment variables in order to use these methods effectively?

I would appreciate any insights or suggestions to resolve this issue. Thank you!

Feature Request - Creating Pins

I am looking to implement a simple capability that automatically creates pins on board to post content generated via my application. The only "user" of the app itself is me. From what I read / understood, the trial access to the API does not allow creation of pins (that others can see) is that correct? To change to standard access it is asking for a video of the app and authenticating users, which I won't have. Can someone please advise if my use case is not meant to be supported? Thanks!

Feature Request - <Issue Title>

What is your feature request? Please describe.

A clear and concise description of what the problem is or what new feature you would like us to add. Ex. I'm always frustrated when [...] or I would like to be able to [...]

Describe the solution you'd like

A clear and concise description of what you want to happen.

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.

Additional context

Add any other context or screenshots about the feature request here.

ModuleNotFoundError

from pinterest.organic.pins import Pin
ModuleNotFoundError: No module named 'pinterest.organic'; 'pinterest' is not a package

Additional Details (please complete the following information):

  • OS and Version: Linux Kali GNU/Linux Rolling
  • SDK Version : Python3.9

Additional Context
I'm using poetry and installed the package

[tool.poetry.dependencies]
pinterest-api-sdk = "^0.2.1"

Feature Request - <Issue Title>

What is your feature request? Please describe.

A clear and concise description of what the problem is or what new feature you would like us to add. Ex. I'm always frustrated when [...] or I would like to be able to [...]

Describe the solution you'd like

A clear and concise description of what you want to happen.

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.

Additional context

Add any other context or screenshots about the feature request here.

BUG - Fetching new access token breaks python code on 401

Describe the bug

A clear and concise description of what the bug is.

To Reproduce

Executing the following code where the refresh token is invalid or has the wrong grants

refresh_token = 'pinr.<REDACTED>'
client_id = '<REDACTED>'
client_secret = '<REDACTED>'

from pinterest.client import PinterestSDKClient
client = PinterestSDKClient.create_client_with_refresh_token(refresh_token, app_id=client_id, app_secret=client_secret)

Yields the error :
AttributeError: 'HTTPResponse' object has no attribute 'body'. Did you mean: '_body'?

Expected behavior

It should throw an error the SdkException in pinterest.utils.refresh_access_token.get_new_access_token with b'{"code":283,"message":"The authorization grant is invalid"}'

Screenshots

Additional Details (please complete the following information):

  • OS and Version: Linux
  • SDK Version v0.2.1

Additional Context

Go SDK + CloudQuery Plugin SDK

Hi Team, hopefully this is right place to ask, if not, I'd appreciate if you can direct me.

I'm the founder of cloudquery.io, a high performance open source ELT framework.

Our users are interested in a Pinterest plugin, but as we cannot maintain all the plugins ourselves, I was curious if this would be an interesting collaboration, where we would help implement an initial source plugin, and you will help maintain it.

This will give your users the ability to sync Pinterest APIs (ads, analytics) to any of their datalakes/data-warehouses/databases easily using any of the growing list of CQ destination plugins.

Best,
Yevgeny

Feature Request - Business Account Auth

Hey. I'm trying to create a pin via API. It works well for my user, but I also want to be able to create pins for my business account.
I've created a business account profile (like https://www.pinterest.com/business/business-access/12../profiles/34../details/) and added myself to publishers. Now I'm looking for a way to authorize the API for the business account or to perform actions on behalf of the business account. How can I achieve this? I think it'll be a useful feature.

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.