如何将Rails应用接入HubSpot API以展示博客内容?
Hey Jake, no need to stress about getting negative feedback—this is a super common setup when migrating a blog to HubSpot while keeping your Rails site as the frontend. Let’s walk through everything you need to know:
Before writing any code, you’ll need to set up a private app in your HubSpot account to get API access:
- Go to HubSpot’s Settings > Integrations > Private Apps
- Create a new app, and under "Scopes", add the content read permissions (specifically
content:blogs:readandcontent:blog-posts:readare key here) - Once created, copy your API key or access token (HubSpot recommends using private app access tokens for better security)
You have two solid options here:
- Use the official HubSpot Ruby gem: This is the easiest route, as it wraps all API endpoints in Ruby methods. Add
gem 'hubspot-api-client'to your Gemfile, runbundle install, then configure it. - Build custom HTTP requests: If you prefer minimal dependencies, use Rails’ built-in
Net::HTTPor a gem likefaradayto call HubSpot’s REST endpoints directly.
For the gem approach, create an initializer to set up the client globally:
Create config/initializers/hubspot.rb:
require 'hubspot_api_client' Hubspot.configure do |config| config.access_token = ENV['HUBSPOT_PRIVATE_APP_TOKEN'] # Or use API key if you're using that method: # config.api_key = ENV['HUBSPOT_API_KEY'] end
Pro tip: Store your credentials in environment variables (use dotenv-rails gem for local development) instead of hardcoding them—never commit secrets to version control!
Short answer: It depends on your use case, but for most scenarios, a dedicated MVC structure will keep your code clean and maintainable.
- If you only need to display a simple list of blog posts and individual post pages: You could get away with adding actions to an existing controller, but a separate
BlogsControlleris still better for organization. - If you plan to add features like caching, filtering posts by category, or custom formatting: A full MVC setup is a must.
Here’s a quick example of a non-ActiveRecord model to wrap HubSpot blog data (create app/models/hubspot_blog_post.rb):
class HubSpotBlogPost def self.all # Fetch all published blog posts from HubSpot response = Hubspot::Content::BlogPost.all(status: 'PUBLISHED') response.results.map { |post| new(post) } end def self.find_by_slug(slug) # Fetch a single post by its slug response = Hubspot::Content::BlogPost.list( slug: slug, status: 'PUBLISHED' ).results.first new(response) if response end attr_reader :title, :body, :published_date, :slug, :featured_image def initialize(hubspot_post) @title = hubspot_post.name @body = hubspot_post.post_body @published_date = hubspot_post.publish_date @slug = hubspot_post.slug @featured_image = hubspot_post.featured_image end end
Then a BlogsController (create app/controllers/blogs_controller.rb):
class BlogsController < ApplicationController def index @posts = Rails.cache.fetch('hubspot_blog_posts', expires_in: 1.hour) do HubSpotBlogPost.all end end def show @post = Rails.cache.fetch("hubspot_blog_post_#{params[:slug]}", expires_in: 2.hours) do HubSpotBlogPost.find_by_slug(params[:slug]) end redirect_to root_path unless @post end end
Note: The caching here is critical—HubSpot has API rate limits, so caching responses will prevent hitting those limits and speed up your site.
As mentioned earlier, put all API configuration in an initializer file (config/initializers/hubspot.rb). This way, the HubSpot client is initialized once when your Rails app starts, and it’s available across all controllers and models.
Never hardcode the API base URL or credentials directly in controllers/models—use environment variables for those values. HubSpot’s gem uses the official API base URL by default, so you won’t need to set it unless you’re using a custom endpoint (unlikely for standard blog access).
Finally, add routes to config/routes.rb:
get '/blog', to: 'blogs#index', as: 'blog' get '/blog/:slug', to: 'blogs#show', as: 'blog_post'
Then create corresponding views in app/views/blogs/—for example, index.html.erb to list posts, and show.html.erb to display a single post using the @post variables from the controller.
内容的提问来源于stack exchange,提问作者Jake

