Getting Started with Contentful and Ruby
This guide will show you how to get started using our Ruby client library to consume content.
Contentful’s Content Delivery API (CDA) is a read-only API for retrieving content from Contentful. All content, both JSON and binary, is fetched from the server closest to a user’s location by using our global CDN.
We publish client libraries for various languages to make developing applications easier.
Requirements
This tutorial assumes that you understand the Contentful data model.
Authentication
For every request, clients need to provide an API key, which is created per space and used to delimit applications and content classes.
You can create an access token using the Contentful web app or the Content Management API.
Installation
First, install the ‘contentful’ gem, with the terminal:
Or you can add it to your Gemfile:
And run bundle install to install the gem and all its dependencies.
Setting up the Contentful client
Once you have installed the gem, you can start using it inside your application.
Initialize the client
You need an API key and a space ID to initialize a client. You can use the API key and space ID pre-filled below from our example space or replace them with your own values.
dynamic_entries: :auto attribute will automatically map the fields in your entries to methods, so that you can use them directly as objects.Getting your content
Contentful separates content between entries, which contain your data and relationships with other content or images, and assets, which represent static content, like images, and are served as files. Read more in our content model guide.
Entries
With the client created, you can now start consuming data from the API.
For example, to request all entries in a space from the API:
Or to request a single entry:
You can specify any of the query parameters accepted by the API, for example:
Using your entry as a Ruby object
Once you have your entry, you can use it as a Ruby object that follows standard Ruby conventions:
You can form complicated queries and interactions with your entries:
In this example you added the include: 2 parameter, which allows the API to resolve links to other related entries.
Using assets
You query assets in a similar way to entries, but the CDA offers more specific features, such as filtering by the type of file. You can also use our Images API, that allows you to manipulate images as you retrieve them.
To query for a single asset:
To query all assets in a space: