Pipedrive NodeJS Client

repository·master·Indexed 42 days ago

https://github.com/pipedrive/client-nodejs

The official Pipedrive REST API client for NodeJS (version 33.7.0), providing typed access to CRM objects such as Deals, Persons, and Organizations. The SDK supports both API v1 and API v2 namespaces and includes comprehensive support for API key authentication and OAuth 2 flows, including automatic token refreshing and onTokenUpdate callbacks.

Tokens
24.7K
Snippets
32
Records
50
Agent score
53%

What's inside Pipedrive

  1. Migrating to the new SDK function signatures

    master

    In newer versions of the SDK (versioned under pipedrive/v1 and pipedrive/v2), function signatures have changed. Instead of passing multiple separate arguments (like id and payload), each function now accepts a single, strongly typed root object containing all necessary parameters.

    // OLD VERSION
    await dealsApi.updateDeal(1, { title: 'Updated Title' });
    
    // NEW VERSION
    await dealsApi.updateDeal({
      id: 1,
      UpdateDealRequest: {
        title: 'Updated Title',
      },
    });
  2. Understand Pipedrive API versions and namespaces

    master

    The SDK supports two distinct API versions. Each version requires its own specific configuration and is accessed via a different namespace. Using the wrong namespace for a version will result in configuration errors.

    • API v1: Use the pipedrive/v1 namespace.
    • API v2: Use the pipedrive/v2 namespace.

    Refer to docs/v1.md and docs/v2.md for the full list of endpoints available in each version.

  3. Authenticate using OAuth 2.0

    master

    The API supports OAuth 2.0 using the accessCode flow.

    Authorization URL: https://oauth.pipedrive.com/oauth/authorize

    When using OAuth, you must request specific scopes to grant your application permission to access different parts of the Pipedrive data.

  4. Authorize a client using OAuth 2

    master

    The OAuth 2 flow involves three main steps:

    1. Obtaining user consent: Redirect the user to the URL provided by oauth2.authorizationUrl.
    2. Handling the response: The OAuth server will redirect back to your redirectUri. If successful, a code query parameter will be present in the URL. If denied, an error query parameter will be present.
    3. Exchanging the code for a token: Use await oauth2.authorize(code) to exchange the authorization code for an access token.
    // 1. Get the URL to redirect the user
    const authUrl = oauth2.authorizationUrl;
    
    // 2. After redirect, exchange the 'code' from the query string
    const token = await oauth2.authorize(code);
  5. Authenticate with a pre-set API token

    master

    For simple integrations, you can use a static API token retrieved from your Pipedrive account settings. Use the Configuration class to provide the apiKey.

    import { Configuration, DealsApi } from 'pipedrive/v2';
    
    // Configure Client with API key authorization
    const apiConfig = new Configuration({
      apiKey: 'YOUR_API_TOKEN_HERE',
    });
    
    // Use the config to instantiate an API class
    const dealsApi = new DealsApi(apiConfig);
    const responseAllDeals = await dealsApi.getDeals();
  6. Perform the OAuth 2 authorization flow

    master

    The OAuth 2 flow involves three main steps:

    1. Obtain user consent: Redirect the user to the URL provided by oauth2.authorizationUrl.
    2. Handle the callback: The Pipedrive server redirects the user back to your redirectUri. If successful, a code query parameter is appended to the URL. If denied, an error parameter is appended.
    3. Exchange code for token: Use await oauth2.authorize(code) to exchange the authorization code for an access token.
    // 1. Get the URL to redirect the user to
    const authUrl = oauth2.authorizationUrl;
    
    // 2. After redirect, extract 'code' from query params and authorize
    // Example: https://example.com/oauth/callback?code=XXXXXXXXXXXXXXXXXXXXXXXXX
    const token = await oauth2.authorize(code);
  7. Use the SDK with an API Token

    master

    To use a pre-set API token (retrieved from your Pipedrive account settings), initialize a Configuration object with the apiKey property and pass it to the desired API class (e.g., DealsApi).

    import { Configuration, DealsApi } from "pipedrive/v1";
    
    // Configure Client with API key authorization
    const apiConfig = new Configuration({
      apiKey: "YOUR_API_TOKEN_HERE",
    });
    
    const dealsApi = new DealsApi(apiConfig);
    const response = await dealsApi.getDeals();
    const { data: deals } = response;
  8. Use the SDK with OAuth 2

    master

    To use OAuth 2, initialize an OAuth2Configuration with your clientId, clientSecret, and redirectUri. Then, create a Configuration object using the getAccessToken and basePath properties from the OAuth2 instance.

    Note: If both an apiKey and an accessToken are provided in the Configuration, the apiKey takes precedence.

    import { OAuth2Configuration, Configuration } from 'pipedrive/v1';
    
    // Configuration parameters and credentials
    const oauth2 = new OAuth2Configuration({
      clientId: "clientId",
      clientSecret: "clientSecret",
      redirectUri: 'redirectUri'
    });
    
    const apiConfig = new Configuration({
        accessToken: oauth2.getAccessToken,
        basePath: oauth2.basePath,
    });
  9. Complete OAuth 2 Express implementation example

    master

    This example demonstrates a full Express.js integration using cookie-session to persist the access token. It handles the initial redirect to authorization, the callback handling, and automatic token updates via onTokenUpdate.

    import express from 'express';
    import { Configuration, DealsApi, OAuth2Configuration } from 'pipedrive/v2';
    import cookieParser from 'cookie-parser';
    import cookieSession from 'cookie-session';
    
    const app = express();
    
    app.use(cookieParser());
    app.use(cookieSession({
        name: 'session',
        keys: ['key1']
    }));
    
    const PORT = 3000;
    
    const oauth2 = new OAuth2Configuration({
        clientId: 'clientId',
        clientSecret: 'clientSecret',
        redirectUri: 'redirectUri'
    });
    
    // Register callback to persist refreshed tokens automatically
    oauth2.onTokenUpdate = function (token) {
      req.session.token = token;
    };
    
    app.get('/', async (req, res) => {
      try {
        // updateToken handles returning null if no token is available
        const token = oauth2.updateToken(req.session?.accessToken);
    
         if (!token) {
            const authUrl = oauth2.authorizationUrl;
            return res.redirect(authUrl);
        }
    
        const apiConfig = new Configuration({
            accessToken: oauth2.getAccessToken,
            basePath: oauth2.basePath,
        });
    
        const dealsApi = new DealsApi(apiConfig);
        const response = await dealsApi.getDeals();
        const { data: deals } = response;
    
        return res.send(deals);
      } catch (error){
          console.error(error)
          return res.status(500).send(error)
      }
    });
    
    app.get('/callback', async (req, res) => {
        try {
            const authCode = req.query.code as string;
            const newAccessToken = await oauth2.authorize(authCode);
    
            req.session.accessToken = newAccessToken;
            return res.redirect('/');
        }catch (error) {
            console.error(error)
            return res.status(500).send(error)
        }
    });
    
    app.listen(PORT);
  10. Refresh OAuth 2 tokens

    master

    Access tokens expire over time. You can manually trigger a refresh using oauth2.tokenRefresh().

    Automatic Refresh: The SDK automatically attempts to refresh the access token before making an authenticated endpoint call if it detects expiration.

    const newToken = await oauth2.tokenRefresh();
  11. Handle token updates with onTokenUpdate

    master

    Because the SDK can automatically refresh tokens in the background, you should register an onTokenUpdate callback. This ensures that whenever a token is refreshed (or initially authorized), your application can persist the new token (e.g., to a database or session).

    // This callback fires upon authorization and every successful token refresh
    oauth2.onTokenUpdate = function (token) {
      // 'token' is the full token object containing updated fields
      saveTokenToDatabase(token);
    };