### Example: Search Deals by Amount and Stage Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/DEALS_API.md This example shows how to search for deals that meet specific criteria, such as a minimum amount and a 'closedwon' deal stage. It limits the returned properties and the number of results. ```ruby search_request = Hubspot::Crm::Deals::PublicObjectSearchRequest.new( filter_groups: [ { filters: [ { property_name: "amount", operator: "GTE", value: "50000" }, { property_name: "dealstage", operator: "EQ", value: "closedwon" } ] } ], properties: ["dealname", "amount", "closedate"], limit: 50 ) results = search.do_search(search_request) ``` -------------------------------- ### Install HubSpot API Ruby Client Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/README.md Install the gem directly or add it to your Gemfile for project integration. ```bash gem install 'hubspot-api-client' ``` ```ruby gem 'hubspot-api-client' ``` -------------------------------- ### Pagination Example Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/types.md Demonstrates how to fetch subsequent pages of results using the cursor provided in the paging object. ```ruby page = basic.get_page(limit: 50) if page.paging && page.paging._next next_page = basic.get_page(after: page.paging._next.after, limit: 50) end ``` -------------------------------- ### Example: Search Active Deals Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/DEALS_API.md This example demonstrates how to search for active deals by excluding 'closedlost' and 'closedwon' stages. It also specifies properties to retrieve and sorts results by close date. ```ruby search_request = Hubspot::Crm::Deals::PublicObjectSearchRequest.new( filter_groups: [ { filters: [ { property_name: "dealstage", operator: "NOT_IN", value: ["closedlost", "closedwon"] } ] } ], properties: ["dealname", "dealstage", "amount"], sorts: [{ property_name: "closedate", direction: "ASCENDING" }], limit: 100 ) results = search.do_search(search_request) puts "Active deals: #{results.total}" ``` -------------------------------- ### Install Hubspot API Client Gem Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/README.md Install the gem using the standard RubyGems command. ```ruby gem install 'hubspot-api-client' ``` -------------------------------- ### Archive Multiple Contacts Example Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/CONTACTS_API.md Example demonstrating how to archive multiple contacts by providing their IDs in a BatchInputSimplePublicObjectId object. ```ruby batch_archive = Hubspot::Crm::Contacts::BatchInputSimplePublicObjectId.new( inputs: [ { id: "123" }, { id: "456" } ] ) batch.archive(batch_archive) ``` -------------------------------- ### Example: Archive Contacts (Ruby) Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/BATCH_OPERATIONS.md Demonstrates how to archive a batch of contacts using their IDs. Ensure the input is formatted as a BatchInputSimplePublicObjectId. ```ruby batch_archive = Hubspot::Crm::Contacts::BatchInputSimplePublicObjectId.new( inputs: [ { id: "contact_123" }, { id: "contact_456" }, { id: "contact_789" } ] ) client.crm.contacts.batch_api.archive(batch_archive) puts "Archived 3 contacts" ``` -------------------------------- ### Perform GET Request Using api_request Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/README.md Example of making a GET request to the contacts endpoint using `api_request` with query parameters for limit and properties. ```ruby require 'hubspot-api-client' client = Hubspot::Client.new(access_token: 'your_access_token') options = { method: "GET", path: "/crm/v3/objects/contacts", qs: { limit: 1, properties: ["email", "last_activity_date"] } } contacts = client.api_request(options) p JSON.parse(contacts.body) ``` -------------------------------- ### Ruby Example for Setting Authentication Headers Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/endpoints.md This Ruby code demonstrates how to set the required Authorization and Content-Type headers for API requests. ```ruby headers = { "Authorization" => "Bearer your_access_token_here", "Content-Type" => "application/json" } ``` -------------------------------- ### Initialize Hubspot Client and Get Contacts Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/README.md Load the gem, initialize the client with an access token, and retrieve a page of contacts. ```ruby # Load the gem require 'hubspot-api-client' # Setup client client = Hubspot::Client.new(access_token: 'your_access_token') # Get contacts contacts = client.crm.contacts.basic_api.get_page ``` -------------------------------- ### Handling 404 Not Found Error Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/errors.md Example of handling a 404 error, which occurs when a requested resource does not exist. ```ruby begin contact = client.crm.contacts.basic_api.get_by_id("nonexistent_id") rescue Hubspot::Crm::Contacts::ApiError => e if e.code == 404 puts "Contact not found" end end ``` -------------------------------- ### PublicMergeInput Example Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/types.md Example of creating a PublicMergeInput object to merge two HubSpot objects. Specifies source and target IDs and field priorities. ```ruby merge = PublicMergeInput.new( from_object_id: "111", to_object_id: "222", merge_fields: { "email" => "toobject", # Use email from target "phone" => "fromobject" # Use phone from source } ) ``` -------------------------------- ### Paginate Through Deal Results Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/DEALS_API.md This example shows how to implement cursor-based pagination to retrieve deals page by page. It uses a loop to fetch subsequent pages until all results are processed. ```ruby after = nil loop do page = basic.get_page(limit: 50, after: after) page.results.each { |deal| process(deal) } break unless page.paging && page.paging._next after = page.paging._next.after end ``` -------------------------------- ### Get All and Specific Owners Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/ADDITIONAL_MODULES.md Shows how to retrieve a paginated list of all owners and fetch a specific owner by ID. ```ruby # Get all owners owners_page = client.crm.owners.basic_api.get_page(limit: 100) owners_page.results.each do |owner| puts "#{owner.properties['firstName']} #{owner.properties['lastName']} - #{owner.properties['email']}" end # Get specific owner owner = client.crm.owners.basic_api.get_by_id("owner_id_123") ``` -------------------------------- ### Make a GET API Request Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/CLIENT_INITIALIZATION.md This snippet shows how to make a direct GET request to the HubSpot API using the `api_request` method. It includes setting query parameters for limiting results and specifying properties. ```ruby require 'hubspot-api-client' client = Hubspot::Client.new(access_token: 'your_access_token') options = { method: "GET", path: "/crm/v3/objects/contacts", qs: { limit: 1, properties: ["email", "lastname"] } } response = client.api_request(options) contacts_data = JSON.parse(response.body) ``` -------------------------------- ### Create Contact Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/CONTACTS_API.md This section details the input model for creating contacts and provides an example of how to handle potential API errors during the creation process. ```APIDOC ## POST /crm/v3/objects/contacts ### Description Creates a new contact in HubSpot. ### Method POST ### Endpoint /crm/v3/objects/contacts ### Parameters #### Request Body - `properties` (Hash) - Required - Contact properties to set. - `associations` (Array) - Optional - Associated objects. ### Request Example ```json { "properties": { "email": "test@example.com", "firstname": "Test", "lastname": "User" } } ``` ### Response #### Success Response (201) - `id` (string) - The unique identifier for the created contact. - `properties` (object) - The properties of the created contact. #### Response Example ```json { "id": "123456789", "properties": { "email": "test@example.com", "firstname": "Test", "lastname": "User", "createdate": "2023-01-01T12:00:00Z", "lastmodifieddate": "2023-01-01T12:00:00Z" } } ``` ``` -------------------------------- ### Accessing CRM Module and Submodules Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/CLIENT_INITIALIZATION.md This example demonstrates how to access the CRM API module and its submodules like contacts and companies after initializing the client. ```ruby # Accessing CRM module crm_client = client.crm # Accessing CRM submodules contacts_client = client.crm.contacts companies_client = client.crm.companies ``` -------------------------------- ### Create a Contact Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/INDEX.md Example of creating a single contact record using the HubSpot API. This operation requires valid contact properties. ```ruby require "hubspot-ruby" client = Hubspot::Client.new({ access_token: "YOUR_PRIVATE_APP_ACCESS_TOKEN" }) contact_properties = { "email": "test.user@example.com", "firstname": "Test", "lastname": "User" } begin response = client.crm.contacts.basic_api.create(contact_properties: contact_properties) puts "Contact created successfully: #{response['id']}" rescue Hubspot::ApiError => e puts "Error creating contact: #{e.message}" end ``` -------------------------------- ### Accessing Batch APIs in Ruby Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/BATCH_OPERATIONS.md Demonstrates how to access the batch API classes for contacts, companies, and deals using the HubSpot Ruby client. Ensure the 'hubspot-api-client' gem is installed and you have an access token. ```ruby require 'hubspot-api-client' client = Hubspot::Client.new(access_token: 'your_token') # Access batch APIs contacts_batch = client.crm.contacts.batch_api companies_batch = client.crm.companies.batch_api deals_batch = client.crm.deals.batch_api ``` -------------------------------- ### Example: Upsert Companies by Domain (Ruby) Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/BATCH_OPERATIONS.md Demonstrates how to upsert companies using their domain as the external identifier. The response includes a 'created' flag indicating whether the record was newly created or updated. ```ruby companies_data = [ { idProperty: "domain", properties: { "domain" => "acme.com", "name" => "Acme Corp", "annualrevenue" => "10000000" } }, { idProperty: "domain", properties: { "domain" => "techcorp.io", "name" => "Tech Corporation", "numberofemployees" => "500" } } ] batch_input = Hubspot::Crm::Companies::BatchInputSimplePublicObjectBatchInputUpsert.new( inputs: companies_data ) response = client.crm.companies.batch_api.upsert(batch_input) response.results.each do |result| puts "Upserted: #{result.id} (created: #{result.created})" end ``` -------------------------------- ### Basic Search Example Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/SEARCH_OPERATIONS.md Demonstrates a basic search for contacts with a specific first name, retrieving email, first name, and last name, and sorting by analytics visits. ```APIDOC ## Basic Search Example ### Description Performs a search for contacts based on a `firstname` property, retrieves specified properties, and sorts the results. ### Method POST ### Endpoint `/crm/v3/objects/contacts/search` ### Parameters #### Request Body - **filter_groups** (array) - Required - Groups of filters to apply to the search. - **filters** (array) - Required - List of filters within a group. - **property_name** (string) - Required - The name of the property to filter on. - **operator** (string) - Required - The comparison operator (e.g., `EQ`, `GT`, `CONTAINS`). - **value** (string) - Required - The value to compare against. - **properties** (array) - Optional - A list of properties to retrieve for each contact. - **sorts** (array) - Optional - A list of properties to sort the results by. - **property_name** (string) - Required - The name of the property to sort on. - **direction** (string) - Required - The sort direction (`ASCENDING` or `DESCENDING`). - **limit** (integer) - Optional - The maximum number of results to return. ### Request Example ```json { "filter_groups": [ { "filters": [ { "property_name": "firstname", "operator": "EQ", "value": "John" } ] } ], "properties": ["email", "firstname", "lastname"], "sorts": [ { "property_name": "hs_analytics_num_visits", "direction": "DESCENDING" } ], "limit": 50 } ``` ### Response #### Success Response (200) - **total** (integer) - The total number of matching records. - **results** (array) - An array of contact objects matching the search criteria. - Each object contains a `properties` field with the requested contact details. #### Response Example ```json { "total": 1, "results": [ { "properties": { "email": "john.doe@example.com", "firstname": "John", "lastname": "Doe" }, "createdAt": "2023-01-01T12:00:00Z", "updatedAt": "2023-01-01T12:00:00Z", "archived": false } ] } ``` ``` -------------------------------- ### Get All Pipelines Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/ADDITIONAL_MODULES.md Retrieves a paginated list of all sales pipelines. Iterates through results to display pipeline labels and stages. ```ruby pipelines = client.crm.pipelines.basic_api.get_page(limit: 50) pipelines.results.each do |pipeline| puts "Pipeline: #{pipeline.properties['label']}" puts "Stages: #{pipeline.properties['stages']}" end ``` -------------------------------- ### Get Deal by ID with Associations (Ruby) Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/DEALS_API.md Fetches a deal by its ID and includes associations with contacts and companies. Iterate through the associated contacts to display their IDs. ```ruby deal = basic.get_by_id( "12345", associations: ["contacts", "companies"] ) deal.associations["contacts"].each do |contact_assoc| puts "Associated contact: #{contact_assoc.id}" end ``` -------------------------------- ### Perform POST Request Using api_request Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/README.md Example of making a POST request to create a contact using `api_request` with a request body containing contact properties. ```ruby require 'hubspot-api-client' client = Hubspot::Client.new(access_token: 'your_access_token') options = { method: "POST", path: "/crm/v3/objects/contacts", body: { "properties": { "email": "some_email@some.com", "lastname": "some_last_name" } } } contacts = client.api_request(options) p JSON.parse(contacts.body) ``` -------------------------------- ### Create Custom Object Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/README.md Example of creating a custom object using the HubSpot API Ruby client. This includes defining labels, properties, and associated objects. ```APIDOC ## Create Custom Object ### Description This endpoint allows for the creation of custom objects within HubSpot. ### Method POST ### Endpoint `/crm/schemas/core_api/create` ### Request Body - **labels** (object) - Required - Defines the singular and plural names for the object. - **singular** (string) - Required - The singular name of the object. - **plural** (string) - Required - The plural name of the object. - **required_properties** (array) - Required - A list of property names that are required for the object. - **searchable_properties** (array) - Optional - A list of property names that should be searchable. - **primary_display_property** (string) - Required - The name of the property to be used as the primary display property. - **secondary_display_properties** (array) - Optional - A list of property names to be used as secondary display properties. - **properties** (array) - Required - An array of property definitions. - **name** (string) - Required - The internal name of the property. - **label** (string) - Required - The display name of the property. - **group_name** (string) - Required - The name of the property group this property belongs to. - **options** (array) - Optional - A list of options for enumeration type properties. - **label** (string) - Required - The display label for the option. - **value** (string) - Required - The value of the option. - **description** (string) - Optional - A description for the option. - **display_order** (integer) - Optional - The order in which to display the option. - **hidden** (boolean) - Optional - Whether the option is hidden. - **display_order** (integer) - Optional - The order in which to display the property. - **type** (string) - Required - The data type of the property (e.g., 'enumeration', 'string'). - **field_type** (string) - Required - The type of field for the property (e.g., 'select'). - **associated_objects** (array) - Optional - A list of object types that this custom object is associated with. - **name** (string) - Required - The unique name of the custom object. ### Request Example ```ruby { "labels": { "singular": "My object", "plural": "My objects" }, "required_properties": ["property001"], "searchable_properties": [], "primary_display_property": "property001", "secondary_display_properties": [], "properties": [ { "name": "property001", "label": "My object property", "group_name": "my_object_information", "options": [ { "label": "Option A", "value": "A", "description": "Choice number one", "display_order": 1, "hidden": false } ], "display_order": 2, "type": "enumeration", "field_type": "select" } ], "associated_objects": ["CONTACT"], "name": "my_object" } ``` ### Response #### Success Response (200) Details of the created custom object. ``` -------------------------------- ### Ruby Example for Direct API Request Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/endpoints.md This Ruby code shows how to make a direct API request using the `api_request` method for endpoints not yet supported by the client library. It includes parsing the JSON response body. ```ruby response = client.api_request( method: "POST", path: "/crm/v3/objects/contacts", body: { properties: { email: "test@example.com" } } ) data = JSON.parse(response.body) ``` -------------------------------- ### Get All Records with Pagination Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/CLIENT_INITIALIZATION.md Demonstrates using the `get_all` helper method to retrieve all records for a CRM object, which handles pagination automatically. ```ruby # Get all contacts (handles pagination internally) all_contacts = client.crm.contacts.basic_api.get_all(properties: ["email", "firstname"]) ``` -------------------------------- ### Existence Operator Example Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/SEARCH_OPERATIONS.md Shows how to use the 'HAS_PROPERTY' existence operator to filter records where a specific property is set. No value is required for this operator. ```ruby { property_name: "phone", operator: "HAS_PROPERTY" } ``` -------------------------------- ### Migrating from API Key to OAuth2 Access Token Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/configuration.md Provides code examples for initializing the HubSpot client using the old API key method (deprecated) and the new OAuth2 access token method. ```ruby # Old (deprecated): client = Hubspot::Client.new(api_key: 'hapikey_xxx') # New (OAuth2): client = Hubspot::Client.new(access_token: 'pat-xxx') ``` -------------------------------- ### Complex Multi-Filter Example Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/SEARCH_OPERATIONS.md Illustrates how to combine multiple filters within a single filter group to perform an AND operation, finding contacts that meet specific criteria. ```APIDOC ## Complex Multi-Filter Examples ### Example 1: Multiple Conditions (AND) ### Description Finds contacts that satisfy multiple conditions simultaneously by placing them within the same filter group, effectively using AND logic. ### Method POST ### Endpoint `/crm/v3/objects/contacts/search` ### Parameters #### Request Body - **filter_groups** (array) - Required - Groups of filters to apply to the search. - **filters** (array) - Required - List of filters within a group. All filters in this array must be true for the group to match. - **property_name** (string) - Required - The name of the property to filter on. - **operator** (string) - Required - The comparison operator (e.g., `EQ`). - **value** (string) - Required - The value to compare against. - **properties** (array) - Optional - A list of properties to retrieve for each contact. - **limit** (integer) - Optional - The maximum number of results to return. ### Request Example ```json { "filter_groups": [ { "filters": [ { "property_name": "hs_lead_status", "operator": "EQ", "value": "QUALIFIED_LEAD" }, { "property_name": "lifecyclestage", "operator": "EQ", "value": "customer" } ] } ], "properties": ["email", "firstname", "lastname", "hs_analytics_revenue"], "limit": 100 } ``` ### Response #### Success Response (200) - **total** (integer) - The total number of matching records. - **results** (array) - An array of contact objects matching the search criteria. #### Response Example ```json { "total": 2, "results": [ { "properties": { "email": "qualified.customer@example.com", "firstname": "Jane", "lastname": "Doe", "hs_analytics_revenue": "5000" }, "createdAt": "2023-02-15T09:00:00Z", "updatedAt": "2023-03-20T14:30:00Z", "archived": false } ] } ``` ``` -------------------------------- ### HubSpot API Pagination Headers Example Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/endpoints.md List responses from the HubSpot API include pagination information in the response body, using a cursor token for subsequent requests. ```json { "results": [...], "paging": { "next": { "after": "cursor_token", "link": "https://api.hubapi.com/..." } } } ``` -------------------------------- ### Search Companies by Revenue Range Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/COMPANIES_API.md Searches for companies within a specific annual revenue range (inclusive). This example filters by 'annualrevenue' using 'GTE' (greater than or equal to) and 'LTE' (less than or equal to) operators. ```ruby search_request = Hubspot::Crm::Companies::PublicObjectSearchRequest.new( filter_groups: [ { filters: [ { property_name: "annualrevenue", operator: "GTE", value: "1000000" }, { property_name: "annualrevenue", operator: "LTE", value: "10000000" } ] } ], properties: ["name", "annualrevenue", "numberofemployees"], limit: 100 ) results = search.do_search(search_request) puts "Companies in revenue range: " + results.total.to_s ``` -------------------------------- ### Create and Search Products Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/ADDITIONAL_MODULES.md Shows how to create a new product with pricing details and search for products by SKU. ```ruby # Create a product input = Hubspot::Crm::Products::SimplePublicObjectInputForCreate.new( properties: { "name" => "Premium Widget", "sku" => "WIDGET-001", "price" => "99.99", "description" => "Our best-selling widget" } ) product = client.crm.products.basic_api.create(input) # Search products search_request = Hubspot::Crm::Products::PublicObjectSearchRequest.new( filter_groups: [{ filters: [{ property_name: "sku", operator: "CONTAINS", value: "WIDGET" }] }], limit: 50 ) results = client.crm.products.search_api.do_search(search_request) ``` -------------------------------- ### Initialize Client and Create/Get Contacts Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/README.md Demonstrates how to initialize the HubSpot client with an access token, create a new contact, and retrieve a paginated list of contacts. ```ruby require 'hubspot-api-client' # Initialize client with OAuth2 access token client = Hubspot::Client.new(access_token: 'your_access_token') # Create a contact input = Hubspot::Crm::Contacts::SimplePublicObjectInputForCreate.new( properties: { "email" => "john@example.com", "firstname" => "John", "lastname" => "Doe" } ) contact = client.crm.contacts.basic_api.create(input) puts "Created contact: #{contact.id}" # Get contacts with pagination page = client.crm.contacts.basic_api.get_page( limit: 50, properties: ["email", "firstname"] ) page.results.each { |c| puts c.properties["email"] } ``` -------------------------------- ### Initialize HubSpot Client and Access Deals API Modules Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/DEALS_API.md Demonstrates how to initialize the HubSpot client with an access token and access different modules within the Deals API. ```ruby require 'hubspot-api-client' client = Hubspot::Client.new(access_token: 'your_token') basic = client.crm.deals.basic_api batch = client.crm.deals.batch_api search = client.crm.deals.search_api ``` -------------------------------- ### Get Custom Object Schema by Type Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/endpoints.md Retrieves a specific custom object schema by its object type. Use this to get details about a particular schema. ```APIDOC ## GET /crm/v3/schemas/{objectType} ### Description Retrieves a specific custom object schema by its object type. ### Method GET ### Endpoint /crm/v3/schemas/{objectType} ### Parameters #### Path Parameters - **objectType** (string) - Required - The object type of the schema to retrieve. ### Response #### Success Response (200) - **schema** (object) - The requested schema object. #### Response Example ```json { "example": "{\"id\": \"2-0-example\", \"name\": \"my_object\", \"labels\": {\"plural\": \"my_objects\", \"singular\": \"my_object\"}, \"createdAt\": \"2023-01-01T12:00:00Z\", \"updatedAt\": \"2023-01-01T12:00:00Z\"}" } ``` ``` -------------------------------- ### Access Products API Modules Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/ADDITIONAL_MODULES.md Demonstrates how to access different API endpoints for managing products. ```ruby client.crm.products.basic_api client.crm.products.batch_api client.crm.products.search_api ``` -------------------------------- ### Initialize Client with Environment Variable Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/README.md Shows how to initialize the HubSpot client using an OAuth2 access token stored in an environment variable. ```ruby client = Hubspot::Client.new(access_token: ENV['HUBSPOT_TOKEN']) ``` -------------------------------- ### Hubspot::Client Initialization Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/CLIENT_INITIALIZATION.md Initializes a new Hubspot::Client instance with provided parameters for authentication and configuration. ```APIDOC ## Hubspot::Client.new(params) ### Description Initializes a new Hubspot::Client instance. This client manages authentication and provides access to all HubSpot API modules. ### Method `initialize(params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **params** (Hash) - Required - Configuration hash containing authentication credentials. * **params[:access_token]** (String) - Optional - OAuth2 access token for API authentication. Required if no other auth method provided. * **params[:api_key]** (String) - Optional - Deprecated HubSpot API key. No longer supported after v13.1.0. * **params[:developer_api_key]** (String) - Optional - Developer API key for authentication. *Note: At least one of `access_token`, `api_key`, or `developer_api_key` must be provided.* ### Request Example ```ruby require 'hubspot-api-client' # Using OAuth2 access token (recommended) client = Hubspot::Client.new(access_token: 'your_oauth2_access_token') # Using developer API key client = Hubspot::Client.new(developer_api_key: 'your_developer_key') ``` ### Response #### Success Response Returns a `Hubspot::Client` instance. #### Response Example ```ruby # client object is returned ``` ### Error Handling Raises `ArgumentError` if no authentication method is provided. ``` -------------------------------- ### Get Contact Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/endpoints.md Retrieves a specific contact by its ID, with options to include associated data and historical properties. ```APIDOC ## GET /crm/v3/objects/contacts/{contactId} ### Description Retrieves a specific contact by its ID. You can specify which properties to return, include historical data, and filter by association types. ### Method GET ### Endpoint /crm/v3/objects/contacts/{contactId} ### Parameters #### Query Parameters - **properties** (string) - Comma-separated properties (e.g., `email,firstname,lastname`) - **propertiesWithHistory** (string) - Properties with history - **associations** (string) - Associated object types - **archived** (boolean) - Include archived contacts - **idProperty** (string) - Alternative identifier property ### Response #### Success Response (200 OK) `SimplePublicObjectWithAssociations` ``` -------------------------------- ### Get All Companies Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/COMPANIES_API.md Retrieves all companies, handling pagination automatically. Useful for fetching the entire company dataset. ```APIDOC ## GET /crm/v3/objects/companies (Get All) ### Description Retrieve all companies with automatic pagination. ### Method GET ### Endpoint /crm/v3/objects/companies ### Response #### Success Response (200) - **Array** ``` -------------------------------- ### Associations Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/COMPANIES_API.md Describes how Companies can be associated with other Hubspot objects like contacts and deals, with an example of retrieving associated records. ```APIDOC ## Associations Companies can be associated with contacts, deals, and other objects. **Example:** ```ruby # Retrieve company with associated contacts and deals company = basic.get_by_id( "12345", associations: ["contacts", "deals"] ) # Access associations contacts = company.associations["contacts"] deals = company.associations["deals"] contacts.each do |assoc| puts assoc.id # Associated contact ID end ``` **Supported Associations:** - contacts - deals - tickets - projects - goals ``` -------------------------------- ### Initialize Hubspot::Client with Developer API Key Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/CLIENT_INITIALIZATION.md Use this snippet to initialize the Hubspot::Client with a developer API key. Ensure you have a valid key. ```ruby require 'hubspot-api-client' # Using developer API key client = Hubspot::Client.new(developer_api_key: 'your_developer_key') ``` -------------------------------- ### create Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/DEALS_API.md Create a single deal with properties and optional associations. ```APIDOC ## POST /crm/v3/objects/deals ### Description Create a single deal with properties and optional associations. ### Method POST ### Endpoint /crm/v3/objects/deals ### Parameters #### Request Body - **simple_public_object_input_for_create** (SimplePublicObjectInputForCreate) - Required - Deal input with properties and associations - **opts** (Hash) - Optional - Optional parameters ### Request Example ```json { "properties": { "dealname": "Big Enterprise Deal", "dealstage": "negotiation", "amount": "100000", "closedate": "2024-12-31", "dealtype": "existingbusiness" }, "associations": [ { "types": [ { "association_category": "HUBSPOT_DEFINED", "association_type_id": 3 } ], "id": "contact_id_123" } ] } ``` ### Response #### Success Response (200) - **SimplePublicObject** - Created deal ``` -------------------------------- ### Get Contact Endpoint Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/endpoints.md Retrieve a specific contact by its ID. Supports querying properties, associations, and archived status. ```http GET /crm/v3/objects/contacts/{contactId} ``` -------------------------------- ### Create and Search Tickets Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/ADDITIONAL_MODULES.md Shows how to create a new support ticket and search for open tickets by priority. ```ruby # Create a support ticket input = Hubspot::Crm::Tickets::SimplePublicObjectInputForCreate.new( properties: { "subject" => "Cannot login to account", "hs_ticket_priority" => "HIGH", "hs_pipeline_stage" => "new", "content" => "Customer reports login failures" }, associations: [ { types: [{ association_category: "HUBSPOT_DEFINED", association_type_id: 16 }], id: "contact_id_123" } ] ) ticket = client.crm.tickets.basic_api.create(input) # Search open tickets by priority search_request = Hubspot::Crm::Tickets::PublicObjectSearchRequest.new( filter_groups: [{ filters: [ { property_name: "hs_ticket_priority", operator: "EQ", value: "HIGH" }, { property_name: "hs_pipeline_stage", operator: "NOT_IN", value: "closed;resolved" } ] }], limit: 100 ) results = client.crm.tickets.search_api.do_search(search_request) ``` -------------------------------- ### Get Contact Page Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/CONTACTS_API.md Retrieve a paginated list of contacts. This method corresponds to the `get_page` method in the `BasicApi` class. ```APIDOC ## GET /crm/v3/objects/contacts ### Description Retrieve a paginated list of contacts. ### Method GET ### Endpoint /crm/v3/objects/contacts ### Parameters #### Query Parameters - **limit** (Integer) - Optional - Max results per page (1-100) - Default: 10 - **after** (String) - Optional - Cursor token for next page - **properties** (Array) - Optional - Properties to return - **properties_with_history** (Array) - Optional - Properties with history - **associations** (Array) - Optional - Associated object types - **archived** (Boolean) - Optional - Include archived contacts - Default: false ### Response #### Success Response (200) - **CollectionResponseSimplePublicObjectWithAssociationsForwardPaging** - Contains a list of contacts and pagination information #### Response Example ```json { "results": [ { "id": "12345", "properties": { "email": "john.doe@example.com", "firstname": "John", "lastname": "Doe" }, "associations": { "companies": { "results": [ { "id": "67890", "type": "company" } ] } } } ], "paging": { "next": { "after": "cursor-token-for-next-page" } } } ``` ``` -------------------------------- ### Create a Line Item on a Deal Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/ADDITIONAL_MODULES.md Shows how to create a new line item and associate it with a specific deal. ```ruby # Create a line item on a deal input = Hubspot::Crm::LineItems::SimplePublicObjectInputForCreate.new( properties: { "hs_product_id" => "product_123", "quantity" => "5", "price" => "99.99" }, associations: [ { types: [{ association_category: "HUBSPOT_DEFINED", association_type_id: 13 }], id: "deal_id_123" # Associate with a deal } ] ) line_item = client.crm.line_items.basic_api.create(input) ``` -------------------------------- ### Get All Records with Pagination Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/CLIENT_INITIALIZATION.md Demonstrates the `get_all` helper method for retrieving all records of a CRM object, which automatically handles pagination. ```APIDOC ## Get All Records with Pagination ### Description Most CRM objects provide a `get_all` helper method that simplifies retrieving all records by automatically handling the pagination process. ### Method `basic_api.get_all(properties:)` ### Parameters #### Keyword Arguments - **properties** (array of strings) - Required - A list of properties to retrieve for each record. ### Request Example ```ruby # Get all contacts (handles pagination internally) all_contacts = client.crm.contacts.basic_api.get_all(properties: ["email", "firstname"]) ``` ``` -------------------------------- ### Making a Custom API Request Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/CLIENT_INITIALIZATION.md Demonstrates how to make a custom API request with specified method, path, headers, body, and base URL. ```APIDOC ## Making a Custom API Request ### Description Allows for making custom API requests by specifying the HTTP method, endpoint path, custom headers, request body, and the base URL. ### Method `client.api_request(options)` ### Parameters #### Options Hash - **method** (string) - Required - The HTTP method (e.g., 'PUT', 'POST'). - **path** (string) - Required - The API endpoint path. - **headers** (hash) - Optional - Custom headers to include in the request. - **body** (hash) - Optional - The request body payload. - **base_url** (string) - Optional - The base URL for the API endpoint. ### Request Example ```ruby options = { method: "PUT", path: "/crm/v3/objects/contacts/contact_id", headers: { "X-Custom-Header" => "custom_value" }, body: { "properties" => { "email" => "newemail@example.com" } }, base_url: "https://api.hubapi.com" } response = client.api_request(options) ``` ``` -------------------------------- ### Full HubSpot Client Configuration Options Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/configuration.md Demonstrates comprehensive configuration options for the HubSpot client, including authentication, connection settings, SSL/TLS, and debugging. Choose the appropriate authentication method and adjust connection parameters as needed. ```ruby client = Hubspot::Client.new( # Authentication (choose one) access_token: 'your_oauth2_access_token', # Recommended developer_api_key: 'your_developer_api_key', # Alternative # Connection settings base_url: 'https://api.hubapi.com', # Default: HubSpot API timeout: 30, # Request timeout in seconds # SSL/TLS settings verify_ssl: true, # Default: verify SSL certificates verify_ssl_host: true, # Default: verify SSL hostname cert_file: '/path/to/cert.pem', # Optional: client certificate key_file: '/path/to/key.pem', # Optional: client key ssl_ca_cert: '/path/to/ca.pem', # Optional: CA certificate # Debugging debugging: false, # Log HTTP requests/responses # Advanced user_agent: 'custom-ruby-client/1.0' ) ``` -------------------------------- ### Handling 400 Bad Request Error Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/errors.md Example of catching a 400 error and parsing the response body to identify invalid properties. ```ruby begin input = Hubspot::Crm::Contacts::SimplePublicObjectInputForCreate.new( properties: { "invalidprop" => "value" } ) contact = client.crm.contacts.basic_api.create(input) rescue Hubspot::Crm::Contacts::ApiError => e if e.code == 400 body = JSON.parse(e.response_body) puts "Invalid property: #{body['message']}" end end ``` -------------------------------- ### Get Contact by ID Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/CONTACTS_API.md Retrieve a contact by its ID with optional properties and associations. This method corresponds to the `get_by_id` method in the `BasicApi` class. ```APIDOC ## GET /crm/v3/objects/contacts/{contactId} ### Description Retrieve a contact by its ID with optional properties and associations. ### Method GET ### Endpoint /crm/v3/objects/contacts/{contactId} ### Parameters #### Path Parameters - **contactId** (String) - Required - The HubSpot contact ID #### Query Parameters - **properties** (Array) - Optional - Specific properties to return (comma-separated) - **properties_with_history** (Array) - Optional - Properties with historical values - **associations** (Array) - Optional - Associated object types to include - **archived** (Boolean) - Optional - Include archived contacts (default: false) - **id_property** (String) - Optional - Alternative identifier property name ### Response #### Success Response (200) - **SimplePublicObjectWithAssociations** - Contact with requested properties and associations #### Response Example ```json { "id": "12345", "properties": { "email": "john.doe@example.com", "firstname": "John", "lastname": "Doe", "phone": "555-1234" }, "associations": { "companies": { "results": [ { "id": "67890", "type": "company" } ] } } } ``` ``` -------------------------------- ### Initialize HubSpot Client with Developer API Key Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/CLIENT_INITIALIZATION.md Initialize the HubSpot client using a developer API key. This method is suitable for development and testing. ```ruby client = Hubspot::Client.new(developer_api_key: 'dev_key') ``` -------------------------------- ### Get Paginated Companies Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/COMPANIES_API.md Retrieves a paginated list of companies, allowing for efficient fetching of large datasets. Supports filtering and sorting. ```APIDOC ## GET /crm/v3/objects/companies ### Description Retrieve a paginated list of companies. ### Method GET ### Endpoint /crm/v3/objects/companies ### Parameters #### Query Parameters - **limit** (Integer) - Optional - Max results per page (1-100) - Default: 10 - **after** (String) - Optional - Pagination cursor - **properties** (Array) - Optional - Properties to return - **properties_with_history** (Array) - Optional - Properties with history - **associations** (Array) - Optional - Associated object types - **archived** (Boolean) - Optional - Include archived ### Response #### Success Response (200) - **CollectionResponseSimplePublicObjectWithAssociationsForwardPaging** ``` -------------------------------- ### Access Companies APIs Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/COMPANIES_API.md Demonstrates how to initialize the HubSpot client and access the different Companies API modules: BasicApi, BatchApi, and SearchApi. ```ruby require 'hubspot-api-client' client = Hubspot::Client.new(access_token: 'your_token') # Access companies APIs basic = client.crm.companies.basic_api batch = client.crm.companies.batch_api search = client.crm.companies.search_api ``` -------------------------------- ### Basic HubSpot Client Initialization Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/configuration.md Initializes the HubSpot client with a minimal configuration using an OAuth2 access token. Ensure you replace 'your_access_token' with a valid token. ```ruby require 'hubspot-api-client' # Minimal configuration (OAuth2 token required) client = Hubspot::Client.new(access_token: 'your_access_token') ``` -------------------------------- ### Access Contacts API Modules Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/CONTACTS_API.md Demonstrates how to initialize the HubSpot client and access the different contacts API modules: BasicApi, BatchApi, and SearchApi. ```ruby require 'hubspot-api-client' client = Hubspot::Client.new(access_token: 'your_token') # Access contacts APIs basic = client.crm.contacts.basic_api batch = client.crm.contacts.batch_api search = client.crm.contacts.search_api ``` -------------------------------- ### Date and Timestamp Filtering Example Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/SEARCH_OPERATIONS.md Shows how to filter contacts based on a date property, converting a date string to a millisecond timestamp for the query. ```APIDOC ## Date and Timestamp Filtering ### Description Filters search results based on date or timestamp properties. Dates should be converted to millisecond timestamps for comparison. ### Method POST ### Endpoint `/crm/v3/objects/contacts/search` ### Parameters #### Request Body - **filter_groups** (array) - Required - Groups of filters to apply to the search. - **filters** (array) - Required - List of filters within a group. - **property_name** (string) - Required - The name of the property to filter on (e.g., `lastmodifieddate`). - **operator** (string) - Required - The comparison operator (e.g., `GTE`, `LT`). - **value** (string) - Required - The date/timestamp value, typically in millisecond timestamp format. - **properties** (array) - Optional - A list of properties to retrieve. - **limit** (integer) - Optional - The maximum number of results to return. ### Request Example ```json { "filter_groups": [ { "filters": [ { "property_name": "lastmodifieddate", "operator": "GTE", "value": "1704067200000" } ] } ], "properties": ["email", "firstname", "lastmodifieddate"], "limit": 100 } ``` ### Response #### Success Response (200) - **total** (integer) - The total number of matching records. - **results** (array) - An array of contact objects matching the search criteria. #### Response Example ```json { "total": 5, "results": [ { "properties": { "email": "contact1@example.com", "firstname": "Alice", "lastmodifieddate": "1704067200000" }, "createdAt": "2023-01-01T10:00:00Z", "updatedAt": "2024-01-01T12:00:00Z", "archived": false } ] } ``` ``` -------------------------------- ### Create a Quote Source: https://github.com/hubspot/hubspot-api-ruby/blob/master/_autodocs/api-reference/ADDITIONAL_MODULES.md Shows how to create a new sales quote and associate it with a contact. ```ruby # Create a quote input = Hubspot::Crm::Quotes::SimplePublicObjectInputForCreate.new( properties: { "hs_quote_number" => "QUOTE-2024-001", "hs_title" => "Premium Plan Quote", "hs_total_deal_value" => "25000", "hs_status" => "DRAFT" }, associations: [ { types: [{ association_category: "HUBSPOT_DEFINED", association_type_id: 10 }], id: "contact_id_123" } ] ) quote = client.crm.quotes.basic_api.create(input) ```