Skip to main content

API Reference

Client and cache

NewContentfulClient(
	spaceID string, 
	clientMode string, 
	clientKey string, 
	optimisticPageSize uint16, 
	logFn func(fields map[string]interface{}, level int, args ...interface{}), 
	logLevel int, 
	debug bool,
	) (*ContentfulClient, error)

Creates a Contentful client, read this for an explanation of all parameters.

SetOfflineFallback(filename string) error

Sets a path to a space export JSON file to be used as a fallback in case Contentful is not reachable when you call UpdateCache() on the client. This ensures availability but can make your content look outdated if the export file is older (and typically it is).

NewOfflineContentfulClient(
	filename string, 
	logFn func(fields map[string]interface{}, level int, args ...interface{}), 
	logLevel int, 
	cacheAssets bool,
	) (*ContentfulClient, error)

Creates an offline Contentful client that loads space data from a JSON file containing a space export.

(cc *ContentfulClient) SetEnvironment(environment string)

Sets the Contentful client's environment. All subsequent API calls will be directed to that environment in the selected space. Pass an empty string to reset to the master environment.

(cc *ContentfulClient) CacheHasContentType(contentTypeID string) bool

Returns true if the specified contentTypeID is cached by the client, false otherwise.

(cc *ContentfulClient) SetCacheUpdateTimeout(seconds int64)

Sets the cache update timeout to the specified length. A new client by default times out caching in 120 seconds. A timeout is used to prevent deadlocks when a service panics and recovers while the gocontentful goroutines are running and the main caching job is waiting for all them to finish.

(cc *ContentfulClient) SetSyncMode(mode bool) error

Switches on/off the cache sync mode. This method will return an error if called on an offline client.

(cc *ContentfulClient) ResetSync()

Resets the sync token: the next call to UpdateCache() will rebuild the cache from scratch.

(cc *ContentfulClient) UpdateCache(ctx context.Context, contentTypes []string, cacheAssets bool) error

Builds or re-builds the entire client cache.

(cc *ContentfulClient) UpdateCacheForEntity(ctx context.Context, sysType string, contentType string, entityID string) error

Updates a single entry or asset (the sysType can take const sysTypeEntry or sysTypeAsset values) in the cache.

Content functions and methods

For these we're assuming a content type named "Person".

NewCfPerson(contentfulClient ...*ContentfulClient) (cfPerson *CfPerson)

Creates a new Person entry. You can manipulate and upsert this later. The contentfulClient parameter is optional but you might want to pass it most of the times or you won't be able to save the entry.

(cc *ContentfulClient) GetAllPerson() (voMap map[string]*CfPerson, err error)

Retrieves all Person entries from the client and returnes a map where the key is the ID of the entry and the value is the Go value object for that entry.

(cc *ContentfulClient) GetFilteredPerson(query *contentful.Query) (voMap map[string]*CfPerson, err error)

Retrieves Person entries matching the specified query.

(cc *ContentfulClient) GetPersonByID(id string, forceNoCache ...bool) (vo *CfPerson, err error)

Retrieves the Person entry with the specified ID. The optional forceNoCache parameter, if true, makes the function bypass the existing cache and load a fresh copy of the entry from Contentful.

(ref ContentfulReferencedEntry) ContentType() (contentType string)

Returns the Sys.ID of the content type of the referenced entry

(cc *ContentfulClient) GetContentTypeOfID(ID string) (contentType string)

Returns the Contentful content type of an entry ID.

(vo *CfPerson) ToReference() (refSys ContentTypeSys)

Converts a value object into a reference that can be added to a reference field of an entry. Note that functions that retrieve referenced entries return a more flexible and useful []*EntryReference (see Quickstart above) but to store a reference you need a ContentTypeSys.

(vo *CfPerson) GetParents() (parents []EntryReference, err error)
(ref *EntryReference) GetParents(cc *ContentfulClient) (parents []EntryReference, err error)

Return a slice of EntryReference objects that represent entries that reference the value object or the entry reference.

Note that in case of parents of an entry reference you need to pass a pointer to a ContentfulClient because EntryReference objects are generic and can't carry any.

(vo *CfPerson) GetPublishingStatus() string

Returns the publishing status of the entry as per the Contentful editor UI. Value returned is one of the following:

const (
  StatusDraft     = "draft"
  StatusChanged   = "changed"
  StatusPublished = "published"
)

Entry field getters and setters

Field getters are named after the field ID in Contentful and return the proper type. For example, if the Person content type has a Symbol (short text) field named 'Name', this will be the getter:

(vo *CfPerson) Name(locale ...string) (string)

The locale parameter is optional and if not passed, the function will return the value for the default locale of the space. If the locale is specified and it's not available for the space, an error is returned. If the locale is valid but a value doesn't exist for the field and locale, the function will return the value for the default locale if that's specified as a fallback locale in the space definition in Contentful, otherwise will return an error.

Possible return types are:

  • string for fields of types Symbol, Text, Date
  • []string for fields of type List
  • float64 for fields of type Integer or Number
  • bool for fields of type Boolean
  • *ContentTypeSys for single reference fields
  • []*ContentTypeSys for multiple reference fields
  • *ContentTypeFieldLocation for fields of type Location
  • *interface for fields of type Object or RichText

If logLevel is set to LogDebug retrieving the value of a field that is not set and so not available in the API response even as a fallback to the default locale will log the event. This can become incredibly verbose, use with care.

Field setters are named after the field ID in Contentful and require to pass in the proper type. See FIELD GETTERS above for a reference. Example:

(vo *CfPerson) SetName(title string, locale ...string) (err error)

Entry write ops (only available for ClientModeCMA)

(vo *CfPerson) UpsertEntry(cc *ContentfulClient) (err error)

Upserts the entry. This will appear as "Draft" (if it's a new entry) or "Changed" if it's already existing. In the latter case, you will need to retrieve the entry with one of the Manage* functions above to acquire the Sys object that contains the version information. Otherwise the API call will fail with a "Version mismatch" error.

(vo *CfPerson) PublishEntry(cc *ContentfulClient) (err error)

Publishes the entry. Note that before publishing you will need to retrieve the entry with one of the Manage* functions above to acquire the Sys object that contains the version information. Otherwise the API call will fail with a "Version mismatch" error. This is needed even if you have just upserted the entry with the function above!

(vo *CfPerson) UnpublishEntry(cc *ContentfulClient) (err error)

Unpublishes the entry. Note that before unpublishing you will need to retrieve the entry with one of the Manage* functions above to acquire the Sys object that contains the version information. Otherwise the API call will fail with a "Version mismatch" error. This is needed even if you have just upserted the entry with the function above!

(vo *CfPerson) UpdateEntry(cc *ContentfulClient) (err error)

Shortcut function that upserts and publishes the entry. Note that before calling this you will need to retrieve the entry with one of the Manage* functions above to acquire the Sys object that contains the version information. Otherwise the API call will fail with a "Version mismatch" error. Using this shortcut function avoids retrieving the entry twice.

(vo *CfPerson) DeleteEntry(cc *ContentfulClient) (err error)

Unpublishes and deletes the entry

Asset functions

(cc *ContentfulClient) DeleteAsset(asset *contentful.Asset) error

Deletes an asset from the space (only available in CMA)

(cc *ContentfulClient) DeleteAssetFromCache(key string) error {

Deletes an asset from the client's cache

(cc *ContentfulClient) GetAllAssets() (map[string]*contentful.Asset, error)

Retrieve all assets from a space

(cc *ContentfulClient) GetAssetByID(id string, forceNoCache ...bool) (*contentful.Asset, error)

Retrieve an asset from a space by its ID. The optional forceNoCache parameter, if true, makes the function bypass the existing cache and load a fresh copy of the asset from Contentful.

NewAssetFromURL(id string, uploadUrl string, imageFileType string, title string, locale ...string) *contentful.Asset

Creates an Asset from an URL of an existing file online (you still need to upsert it later).

ToAssetReference(asset *contentful.Asset) (refSys ContentTypeSys)

Converts the asset to a reference. You need to do this before you add the asset to a reference field of an entry.

(cc *ContentfulClient) DeleteAsset(asset *contentful.Asset) error

Deletes an asset from a space by its ID (only available for ClientModeCMA)

Other helper functions and methods

(cc *ContentfulClient) BrokenReferences() (brokenReferences []BrokenReference)

Returns a slice of BrokenReference objects with details of where entries have been referenced but they are not found in the cache. This might naturally return false positives for content types that are in the space but not included in the cache.

FieldToObject(jsonField interface{}, targetObject interface{}) error

Converts a JSON field into an object. Make sure you pass a pointer to an object which type has JSON definition for all fields you want to retrieve.

HtmlToRichText(htmlSrc string) *RichTextNode

Converts an HTML fragment to a RichTextNode. This is useful to migrate data from third-party systems to Contentful or support HTML paste operations in Web applications. It currently supports headings, paragraphs, hyperlinks, italic and bold tags, horizontal rules, blockquote, ordered and unordered lists, code. Unknown tags are stripped. This function doesn't return any error as it converts the input text into something as good as possible, without validation.

RichTextToHtml(rt interface{}, linkResolver LinkResolverFunc, entryLinkResolver EntryLinkResolverFunc, imageResolver ImageResolverFunc, locale Locale) (string, error) {

Converts an interface representing a Contentful RichText value (usually from a field getter) into HTML. The function takes in three (optional) functions as parameters to resolve hyperlink URLs, permalinks to entries and to derive IMG tag attributes for embedded image assets. The three functions return a map of attributes for the HTML tag the RichTextToHtml function will emit (either an A or an IMG) and have the following signature. Note that the ImageResolverFunc function must return a customHTML value that can be empty but if set it will substitute the IMG tag with the returned HTML snippet. This allows you to emit custom mark-up for your images, e.g. a PICTURE tag.

type LinkResolverFunc func(url string) (resolvedAttrs map[string]string, resolveError error)

type EntryLinkResolverFunc func(entryID string, locale Locale) (resolvedAttrs map[string]string, resolveError error)

type ImageResolverFunc func(assetID string, locale Locale) (attrs map[string]string, customHTML string, resolveError error)

type EmbeddedEntryResolverFunc func(entryID string, locale Locale) (html string, resolveError error)

All the three functions above can be passed as nil with different levels of graceful degrading.

Constants and global variables

Each generated content type library file exports a constant with the Contentful ID of the content type itself, for example in contentful_vo_lib_person.go:

const ContentTypePerson = "person"

Constants are available for each locale supported by the space at the time of code generation, e.g.:

const SpaceLocaleGerman Locale = "de"
const SpaceLocaleFrench Locale = "fr"
const defaultLocale Locale = SpaceLocaleGerman

Four levels of logging are supported (even if only partially used at this time):

const (
    LogDebug = 0
    LogInfo  = 1
    LogWarn  = 2
    LogError = 3
)

A global variable named SpaceContentTypeInfoMap contains an ID-indexed map of all content types with their names and descriptions