Appearance
Are you an LLM? You can read better optimized documentation at /configuration/contentful_setup.md for this page in Markdown format
Contentful setup
Overview
This document provides detailed instructions for configuring the application's integration with the Contentful headless CMS. A correct setup is essential for fetching and displaying content. This guide covers creating a Contentful account, configuring API keys in the application, and understanding the specific implementation details of this project.
For a higher-level overview of how Contentful fits into the application's architecture, please see the Contentful Integration Architecture document.
Creating a Contentful account
Before you can configure the application, you need a Contentful account.
- Navigate to the Contentful sign-up page.
- Complete the registration process. Contentful offers a free community plan which is sufficient for development and testing purposes.
Creating a space
In Contentful, a "space" is a self-contained repository for all content related to a single project. You will need to create a space to hold the application's content.
- Log in to your Contentful account.
- From the main dashboard, click on "Create a space".
- Choose the "Community" (free) plan unless you have specific organizational requirements.
- Give your space a name (e.g., "TheExampleApp Dev").
- Select "Create an empty space".
- Once the space is created, you will be taken to its dashboard.
Obtaining API keys
The application requires three pieces of information from your Contentful space to communicate with the API:
- Space ID: A unique identifier for your content space.
- Content Delivery API Key: A read-only key for accessing published content. This is used in production.
- Content Preview API Key: A read-only key for accessing draft and published content. This is used for development and previewing unpublished changes.
To find these keys:
- In your Contentful space, navigate to Settings > API keys.
- The Space ID is displayed prominently at the top of this page.
- Under the Content delivery / preview tokens tab, you will find your API keys. There is typically one key pair generated by default.
- The Content Delivery API - access token is your
DeliveryApiKey. - The Content Preview API - access token is your
PreviewApiKey.
- The Content Delivery API - access token is your
Keep these values secure and ready for the next step.
Configuration files
The application uses ASP.NET Core's configuration system, primarily driven by appsettings.json files. The Contentful credentials are stored in a ContentfulOptions section.
- Open
TheExampleApp/appsettings.json. - Locate the
ContentfulOptionssection and replace the placeholder values with the keys you obtained from your Contentful space.
json:TheExampleApp/appsettings.json
{
// ... other settings
"ContentfulOptions": {
"DeliveryApiKey": "YOUR_CONTENT_DELIVERY_API_KEY",
"PreviewApiKey": "YOUR_CONTENT_PREVIEW_API_KEY",
"SpaceId": "YOUR_SPACE_ID",
"UsePreviewApi": false
}
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
The application loads this configuration during startup using the contentful.aspnetcore SDK's extension method.
csharp:TheExampleApp/Startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// ...
// This extension method reads the "ContentfulOptions" section from the configuration
// (e.g., appsettings.json) and registers the necessary Contentful services.
services.AddContentful(Configuration);
// ...
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Environment-Specific Configuration
For different environments like Development or Staging, you can create appsettings.Development.json or appsettings.Staging.json to override the base configuration.
The project includes an appsettings.Staging.json file that contains a complete ContentfulOptions configuration for the staging environment, including all API keys and the Space ID. This demonstrates the pattern for environment-specific Contentful configuration.
For development environments, you can create or modify appsettings.Development.json to enable the Preview API:
json:TheExampleApp/appsettings.Development.json
{
"Logging": {
// ... existing logging settings
},
"ContentfulOptions": {
"UsePreviewApi": true
}
}1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
This follows the standard ASP.NET Core configuration hierarchy. For more details on service registration, see the Services Configuration documentation.
Environment variables
For production and CI/CD environments, it is best practice to configure credentials using environment variables rather than committing them to appsettings.json. The ASP.NET Core configuration provider will automatically map environment variables to the configuration model.
Use the following format, with a double underscore (__) to denote JSON hierarchy:
ContentfulOptions__DeliveryApiKeyContentfulOptions__PreviewApiKeyContentfulOptions__SpaceIdContentfulOptions__UsePreviewApi
These variables will override any values present in the appsettings.json files. For a comprehensive guide, refer to Deployment: Environment Variables.
Content model setup
The application code is written to expect a specific set of Content Types (the "Content Model") within your Contentful space. Based on the route conventions in Startup.cs, these likely include types such as Course and Lesson.
csharp:TheExampleApp/Startup.cs
// ...
services.AddMvc().AddRazorPagesOptions(
options => {
options.Conventions.AddPageRoute("/Courses", "Courses/Categories/{category?}");
options.Conventions.AddPageRoute("/Courses/Index", "Courses/{slug}/lessons");
options.Conventions.AddPageRoute("/Courses/Lessons", "Courses/{slug}/lessons/{lessonSlug}");
});
// ...1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
You have two options:
- Import a Content Model: If the project provides a Contentful export file (e.g.,
export.json), you can use the Contentful CLI to import the entire content model and sample content into your space. This is the recommended approach. - Manual Creation: If no export is available, you will need to manually create the required Content Types and their fields in the Contentful web app. Refer to the Contentful Integration Architecture document for details on the expected fields and relationships.
Sample content
The default appsettings.json file is pre-configured with credentials for a public, read-only Contentful example space (spaceId: "qz0n5cdakyl9").
json:TheExampleApp/appsettings.json
"ContentfulOptions": {
"DeliveryApiKey": "df2a18b8a5b4426741408fc95fa4331c7388d502318c44a5b22b167c3c1b1d03",
"PreviewApiKey": "10145c6d864960fdca694014ae5e7bdaa7de514a1b5d7fd8bd24027f90c49bbc",
"SpaceId": "qz0n5cdakyl9",
"UsePreviewApi": false
}1
2
3
4
5
6
2
3
4
5
6
This allows developers to run the application immediately after cloning the repository without any initial Contentful setup. However, you cannot write to this space. For active development, you must switch to your own space by updating the configuration as described above.
API mode selection
The application can fetch content using either Contentful's Delivery API or Preview API. This is controlled by the UsePreviewApi boolean flag in the configuration.
UsePreviewApi | API Used | Content Fetched | Recommended Environment |
|---|---|---|---|
false | Delivery API | Published content only | Production, Staging |
true | Preview API | Draft and Published content | Development |
Advanced: Runtime Credential Switching
This application includes a custom feature that allows Contentful credentials and the API mode to be changed at runtime for the current user's session. This is intended for demonstration purposes (e.g., allowing a user to input their own API keys to preview the app with their content) and is not a standard feature of the contentful.aspnetcore library.
This is implemented via the ContentfulOptionsManager class, which overrides the default IOptions<ContentfulOptions> behavior.
csharp:TheExampleApp/Configuration/ContentfulOptionsManager.cs
/// <summary>
/// Class used to configure whether the current session should use the application configuration or options from session.
/// This to allow injecting different credentials at runtime.
/// </summary>
/// <remarks>
/// This class is normally not needed in your application. It is only present to allow switching credentials at runtime,
/// which is not something every application needs.
/// </remarks>
public class ContentfulOptionsManager : IContentfulOptionsManager
{
// ...
public ContentfulOptions Options {
get {
// Check if there are ContentfulOptions stored in the user's session
var sessionString = _accessor.HttpContext.Session.GetString(nameof(ContentfulOptions));
if (!string.IsNullOrEmpty(sessionString))
{
// If so, use them instead of the ones from appsettings.json
return JsonConvert.DeserializeObject<ContentfulOptions>(sessionString);
}
// Otherwise, fall back to the default options from configuration
return _options;
}
}
// ...
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
This manager is registered in Startup.cs to replace the standard options mechanism, ensuring that every request for IContentfulClient receives the potentially session-specific options. Developers maintaining this system should be aware of this custom logic, as it can affect which Contentful space and API are being used for a given request.