Appearance
Are you an LLM? You can read better optimized documentation at /configuration/contentful_setup.md for this page in Markdown format
Contentful setup
Note: This repo is no longer officially maintained as of Jan, 2023. Feel free to use it, fork it and patch it for your own needs.
This document provides a comprehensive guide for developers on setting up and configuring the Contentful headless CMS for TheExampleApp. It covers both read-only and read-write access modes, application configuration, and the underlying implementation for managing Contentful credentials.
Read-only access
The application is configured to work out-of-the-box with a read-only connection to a default Contentful demo space. This mode is ideal for quickly running the application and exploring its features without any setup.
Using the default demo space
By default, the application uses credentials for a pre-populated Contentful space. These credentials are hardcoded in the appsettings.json file and provide read-only access via the Contentful Delivery API.
json
{
// ... other settings
"ContentfulOptions": {
"DeliveryApiKey": "df2a18b8a5b4426741408fc95fa4331c7388d502318c44a5b22b167c3c1b1d03",
"PreviewApiKey": "10145c6d864960fdca694014ae5e7bdaa7de514a1b5d7fd8bd24027f90c49bbc",
"SpaceId": "qz0n5cdakyl9",
"UsePreviewApi": false
}
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Understanding delivery tokens
The DeliveryApiKey is a Delivery API token. This token is public and safe to expose in client-side applications. It only grants permission to retrieve published content from the Contentful space. It cannot be used to create, edit, or delete content, nor can it be used to view draft content.
To run the application in this mode, simply clone the repository and run the application:
bash
# Clone the repository
git clone https://github.com/contentful/the-example-app.csharp.git
# Restore .NET dependencies
dotnet restore
# Run the application
dotnet run1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
The application will be available at http://localhost:3000.
Read and write access (recommended)
To fully experience the Contentful workflow, including content creation and editing, you must connect the application to a personal Contentful space with read and write access. This involves creating a new space, seeding it with the required content model, and configuring the application with your new API keys.
For a general overview of getting started, see the Quick Start Guide.
Step 1: Install the Contentful CLI
The Contentful CLI is required to create and seed a new space from your terminal.
bash
# Install the Contentful CLI via npm
npm install -g contentful-cli1
2
2
Step 2: Create a new space
Log in to your Contentful account. The CLI will guide you through the process if you don't have an account. Then, create a new space.
bash
# Log in to Contentful
contentful login
# Create a new space, which will output a new SPACE_ID
contentful space create --name 'My space for the example app'1
2
3
4
5
2
3
4
5
Step 3: Seed the space with content
Use the space seed command to import the necessary content types and sample content into your newly created space. Replace <SPACE_ID> with the ID returned from the previous step.
bash
# Seed the space using the 'the-example-app' template
contentful space seed -s '<SPACE_ID>' -t the-example-app1
2
2
Step 4: Obtain API keys
Navigate to your new space in the Contentful web app. Go to Settings > API keys. Here you will find the Space ID and the Content Delivery API - access token. You will also need to create a new Content Preview API - access token.
You will need the following three values:
- Space ID: The unique identifier for your Contentful space.
- Delivery Access Token: The
Content Delivery APItoken. - Preview Access Token: The
Content Preview APItoken.
Configuring the application
Once you have your personal space credentials, you need to configure the application to use them. This application provides two ways to manage credentials: through the standard appsettings.json file and through a dynamic, session-based override mechanism.
Adding credentials to appsettings.json
The most straightforward way to configure your credentials is by updating the ContentfulOptions section in appsettings.json. This is the recommended approach for persistent local development.
For more information on application configuration, see Application Settings.
json
{
// ...
"ContentfulOptions": {
"DeliveryApiKey": "<YOUR_DELIVERY_ACCESS_TOKEN>",
"PreviewApiKey": "<YOUR_PREVIEW_ACCESS_TOKEN>",
"SpaceId": "<YOUR_SPACE_ID>",
"UsePreviewApi": false
}
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Runtime credential management
This example application includes a sophisticated mechanism for changing Contentful credentials at runtime without requiring an application restart. This is primarily to demonstrate switching between the demo space and a user's personal space via the /settings page.
This is managed by the ContentfulOptionsManager class, which acts as a proxy for ContentfulOptions.
csharp
/// <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>
public class ContentfulOptionsManager : IContentfulOptionsManager
{
private ContentfulOptions _options;
private readonly IHttpContextAccessor _accessor;
// ... constructor ...
/// <summary>
/// Gets the currently configured <see cref="ContentfulOptions"/> either from session, if present, or from the application configuration.
/// </summary>
public ContentfulOptions Options {
get {
// Check if there are options stored in the current user's session
var sessionString = _accessor.HttpContext.Session.GetString(nameof(ContentfulOptions));
if (!string.IsNullOrEmpty(sessionString))
{
// If so, deserialize and return them
return JsonConvert.DeserializeObject<ContentfulOptions>(sessionString);
}
// Otherwise, return the default options from appsettings.json
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
28
29
30
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
28
29
30
This manager is registered in Startup.cs along with a custom factory for IContentfulClient. This ensures that on each request, the ContentfulClient is instantiated with the correct options—either from the session or the base configuration.
csharp
public void ConfigureServices(IServiceCollection services)
{
// ...
// Register the manager as a singleton
services.AddSingleton<IContentfulOptionsManager, ContentfulOptionsManager>();
// Register the ContentfulClient with a transient lifetime, using a factory
services.AddTransient<IContentfulClient, ContentfulClient>((ip) => {
var client = ip.GetService<HttpClient>();
// The factory retrieves the current options from our manager for each request
var options = ip.GetService<IContentfulOptionsManager>().Options;
var contentfulClient = new ContentfulClient(client, options);
// ...
return contentfulClient;
});
// ...
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Note: This runtime switching mechanism is a feature specific to this example application. In most production scenarios, you would configure
ContentfulOptionsdirectly from your configuration source (appsettings.json, environment variables, etc.) and would not need theContentfulOptionsManager.
Testing the connection
The application includes robust validation to ensure the provided credentials are correct. This validation is triggered when you submit new credentials on the /settings page.
Connection validation logic
The validation logic resides in the Validate method of the SelectedOptions class, which is part of the Settings.cshtml.cs PageModel. It performs live API calls to Contentful to verify the tokens and Space ID.
The process is as follows:
- Check that all required fields (
SpaceId,AccessToken,PreviewToken) are filled. - Instantiate a
ContentfulClientwith the Delivery API token. - Attempt to fetch the space details (
client.GetSpace().Result). - Catch any
ContentfulExceptionand map the HTTP status code to a user-friendly validation error:401 Unauthorized: Indicates an invalid Delivery API token.404 Not Found: Indicates an invalid Space ID.
- Repeat the process for the Preview API token by creating a new client with
UsePreviewApiset totrue.
csharp
// Inside the SelectedOptions.Validate method
private IEnumerable<ValidationResult> MakeTestCalls(HttpClient httpClient, IContentfulClient contentfulClient, IViewLocalizer localizer)
{
ValidationResult validationResult = null;
// 1. Test the Delivery API credentials
try
{
var space = contentfulClient.GetSpace().Result;
}
catch (AggregateException ae)
{
ae.Handle((ce) => {
if (ce is ContentfulException)
{
if ((ce as ContentfulException).StatusCode == 401)
{
validationResult = new ValidationResult(localizer["deliveryKeyInvalidLabel"].Value, new[] { nameof(AccessToken) });
}
else if ((ce as ContentfulException).StatusCode == 404)
{
validationResult = new ValidationResult(localizer["spaceOrTokenInvalid"].Value, new[] { nameof(SpaceId) });
}
// ... other error handling
return true;
}
return false;
});
}
// ...
// 2. Test the Preview API credentials (similar logic)
// ...
}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
28
29
30
31
32
33
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
28
29
30
31
32
33
Resetting to default credentials
If you have configured custom credentials in your session and want to revert to the default credentials defined in appsettings.json, you can use the reset functionality available on the /settings page. This clears any session-stored credentials and reverts the application to use the base configuration.
csharp
/// <summary>
/// Post action to reset session credentials to the default ones.
/// </summary>
public IActionResult OnPostResetCredentials()
{
HttpContext.Session.SetString(nameof(ContentfulOptions), "");
return RedirectToPage("Settings");
}1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
This is particularly useful when switching between your personal space and the demo space during development.
Enabling editorial features
Once you are using your read-write enabled space, you can enable editorial features. This adds an "Edit" button to content entries, which links directly to the entry in the Contentful web app. It also displays draft and pending changes indicators.
To enable these features, add the ?editorial_features=enabled query parameter to the URL:
http://localhost:3000?editorial_features=enabled
This setting is persisted in the user's session. For more details on this functionality, see the Editorial Features documentation. For more on the different APIs, see API Configuration.