Set up the headless Optimizely Forms API
Set up the headless Optimizely Forms API to serve forms from your Optimizely Content Management System (CMS) 13 site to a decoupled front end. The front end loads each form through the API and sends visitor input back to CMS. CMS stores these submissions the same way it stores submissions from forms it renders.
Prerequisites
Your CMS site needs the following before you install the API:
- A CMS 13 site that runs on .NET 10.
- Optimizely Forms 6.0.1 or later. If your site does not have this package, the Optimizely.Cms.Forms.Service package installs it for you.
- Hypertext Transfer Protocol Secure (HTTPS) on the CMS site. Outside the Development environment, the API accepts access tokens only from an authority that uses HTTPS.
Install the packages
The API requires the following NuGet packages from the Optimizely NuGet feed:
- Optimizely.Cms.Forms.Service – Adds the Forms REST API.
- EPiServer.OpenIDConnect – Issues the OpenID Connect (OIDC) access tokens that the submission endpoints require.
Install the packages with the .NET CLI:
- Open a terminal in the folder that contains your CMS project file (.csproj).
- If your NuGet configuration does not include the Optimizely NuGet feed, add it:
dotnet nuget add source https://api.nuget.optimizely.com/v3/index.json --name Optimizely- Install the Forms API package:
dotnet add package Optimizely.Cms.Forms.Service- Install the OpenID Connect package:
dotnet add package EPiServer.OpenIDConnectConfigure OpenID Connect
The submission endpoints accept requests only with a valid bearer token. EPiServer.OpenIDConnect issues these tokens from your CMS site.
Register a client application for the front end:
- In Startup.cs, add the following code to ConfigureServices:
var useDevelopmentCertificate = _webHostingEnvironment.IsDevelopment();
services.AddOpenIDConnect<ApplicationUser>(
useDevelopmentCertificate: useDevelopmentCertificate,
signingCertificate: useDevelopmentCertificate ? null : signingCertificate,
encryptionCertificate: useDevelopmentCertificate ? null : encryptionCertificate,
createSchema: true,
options =>
{
options.AllowResourceOwnerPasswordFlow = true;
options.Applications.Add(new OpenIDConnectApplication
{
ClientId = "FRONTEND_CLIENT_ID",
Scopes =
{
OpenIddictConstants.Scopes.OpenId
},
});
});- Replace FRONTEND_CLIENT_ID with the client ID that your front end sends when it requests a token.
- Load the signing and encryption certificates from your secrets management solution, such as Azure Key Vault. Assign them to the signingCertificate and encryptionCertificate variables. The code uses development certificates only in the Development environment.
- If your front end does not sign in visitors with FormAuthenticate or FormLogin, remove the AllowResourceOwnerPasswordFlow line.
Important With the resource owner password flow, your front end collects the visitor's user name and password. It sends them to the CMS token endpoint. Enable it only for a front end that you own, and serve both sites over HTTPS.
Share the token keys with the API
The Forms API validates each access token with the signing and encryption keys that EPiServer.OpenIDConnect uses. Copy these keys to each API client:
- Add the following post-configure class to your CMS project:
using Microsoft.Extensions.Options;
using OpenIddict.Server;
using Optimizely.Cms.Forms;
public class FormServiceOptionsPostConfigure : IPostConfigureOptions<OptimizelyFormsServiceOptions>
{
private readonly OpenIddictServerOptions _options;
public FormServiceOptionsPostConfigure(IOptions<OpenIddictServerOptions> options)
{
_options = options.Value;
}
public void PostConfigure(string? name, OptimizelyFormsServiceOptions options)
{
foreach (var client in options.OpenIDConnectClients)
{
foreach (var key in _options.EncryptionCredentials.Select(c => c.Key))
{
client.EncryptionKeys.Add(key);
}
foreach (var key in _options.SigningCredentials.Select(c => c.Key))
{
client.SigningKeys.Add(key);
}
}
}
}- Register the class in ConfigureServices:
services.TryAddEnumerable(
ServiceDescriptor.Singleton<IPostConfigureOptions<OptimizelyFormsServiceOptions>, FormServiceOptionsPostConfigure>());Register the Forms API
Register the Forms API so your CMS site serves the /_forms/v1 endpoints:
- In ConfigureServices, call AddOptimizelyFormsService. The method also registers Optimizely Forms, so you do not need a separate AddForms call:
services.AddOptimizelyFormsService(options =>
{
options.FormCorsPolicy = new FormCorsPolicy
{
// List each front-end origin. Do not use "*" with credentials.
AllowOrigins = ["https://www.example.com"],
AllowCredentials = true
};
options.OpenIDConnectClients.Add(new()
{
Authority = "https://cms.example.com",
ClientId = "FRONTEND_CLIENT_ID"
});
});- Replace https://www.example.com in AllowOrigins with each front-end origin that calls the API.
- Replace https://cms.example.com in Authority with the URL of your CMS site.
- Replace FRONTEND_CLIENT_ID with the client ID that you registered with AddOpenIDConnect.
The OptimizelyFormsServiceOptions class has the following options:
- FormCorsPolicy – Sets the cross-origin resource sharing (CORS) policy for the API. AllowOrigins lists the front-end origins that can call the API. AllowCredentials lets browsers send credentials with requests.
- OpenIDConnectClients – Lists the token issuers that the API trusts. Set Authority to the URL of the site that issues tokens. When EPiServer.OpenIDConnect issues the tokens, the authority is your CMS site URL. The API accepts any valid token from a listed authority. ClientId does not limit which clients can submit.
- EnableOpenApiDocumentation – Serves the OpenAPI specification at /_forms/v1/docs/openapi.json. By default, the specification is available only in the Development environment.
- MaxRequestBodySize – Sets the largest submission request, in bytes, that the API accepts. The default is 30000000, about 30 megabytes.
The API also reads these options from the Optimizely:Forms:Service section of appsettings.json. Values that you set in code override values from configuration.
Configure the middleware
The Forms API runs its own authentication and authorization for /_forms/v1. Your CMS site still needs them for other endpoints, such as the CMS UI and the OpenID Connect token endpoint.
- In Configure, add authentication and authorization after UseRouting and before UseEndpoints:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapContent();
});- If the browser requests tokens directly, add your front-end origins to the CMS site's CORS policy. The token endpoint is outside the Forms API, so FormCorsPolicy does not cover it.
Verify the API
Request a published form to confirm that the API serves form data:
- Get the form key. The form key is the form's content globally unique identifier (GUID), without hyphens.
- Send the following request from a browser or an API client such as Postman:
GET https://cms.example.com/_forms/v1/forms/FORM_KEY?locale=en- Confirm that the API returns 200 OK and the form structure in JavaScript Object Notation (JSON). The following example shows part of the response:
{
"key": "41a07e4d3a634cc581f399caac75789c",
"properties": {
"title": "Contact us",
"allowAnonymousSubmission": true,
"allowMultipleSubmission": false,
"showNavigationBar": false
},
"formElements": [
{
"key": "2933aa8d3e794ccf89ff63bd9746d9f8",
"contentType": "TextboxElementBlock",
"displayName": "Name",
"properties": {
"label": "Name",
"validators": [
{
"type": "RequiredValidator",
"model": {
"message": "This field is required."
}
}
]
},
"localizations": {}
}
],
"locale": "en",
"localizations": {}
}The API returns 404 Not Found when no form matches the key.
Get an access token
Every submission request needs a bearer token, including submissions to forms that allow anonymous submission. With the resource owner password flow, get a token from the EPiServer.OpenIDConnect token endpoint:
- Send the following request:
POST https://cms.example.com/api/episerver/connect/token
Content-Type: application/x-www-form-urlencoded
grant_type=password&client_id=FRONTEND_CLIENT_ID&username=USER_NAME&password=PASSWORD- Copy the token from the access_token property of the response.
- Send the token in the Authorization header of each submission request, such as Authorization: Bearer ACCESS_TOKEN.
API endpoints
The API serves the following endpoints under /_forms/v1:
- GET /_forms/v1/forms/FORM_KEY – Gets a form. Accepts an optional locale query parameter. Does not require a token.
- PUT /_forms/v1/forms – Submits a form or one step of a multi-step form. Requires a token.
- GET /_forms/v1/forms/FORM_KEY/submissions/SUBMISSION_KEY – Gets one submission. Accepts optional locale and includeInactiveFields query parameters. Requires a token for a user who has permission to view form submissions.
- GET /_forms/v1/forms/FORM_KEY/submissions – Lists submissions for a form. Accepts optional locales, finalizedOnly, includeInactiveFields, pageIndex, and pageSize query parameters. Requires a token for a user who has permission to view form submissions.
Submit a form
Send a PUT request to /_forms/v1/forms. The API accepts application/json and multipart/form-data requests. Use multipart/form-data when the form contains a file upload element.
The request body has the following fields:
- formKey – The key of the form.
- locale – The language of the submitted form, such as en.
- isFinalized – Set to true on the last step to complete the submission.
- submissionKey – The key that the previous step returned in a multi-step form. Leave it empty on the first step.
- hostedPageUrl – The URL of the page that displays the form.
- currentStep – The zero-based index of the submitted step.
- fields – The submitted values, keyed by form element key.
Submit JSON data
The following example submits a single-step form as JSON:
PUT https://cms.example.com/_forms/v1/forms
Content-Type: application/json
Authorization: Bearer ACCESS_TOKEN
{
"formKey": "6001a245d28a4419baf28f36fc3cf2a9",
"locale": "en",
"isFinalized": true,
"submissionKey": "",
"hostedPageUrl": "/en/contact/",
"currentStep": 0,
"fields": {
"fd8c0ce15f56440abee3358a9fe9c9d8": "Jane Doe",
"b176ccda9f9f4ea4b87d57cf1eac8210": "[email protected]"
}
}Submit files
For multipart/form-data, put the JSON body in a part named data. Add each file as its own part. The JavaScript SDK names each file part after the file upload element key, followed by _file_ and a zero-based index.
The following example submits one text value and one file. It uses the SDK's file part names:
PUT https://cms.example.com/_forms/v1/forms
Content-Type: multipart/form-data; boundary=----FormBoundary7MA4YWxkTrZu0gW
Authorization: Bearer ACCESS_TOKEN
------FormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="data"
{
"formKey": "6001a245d28a4419baf28f36fc3cf2a9",
"locale": "en",
"isFinalized": true,
"submissionKey": "",
"hostedPageUrl": "/en/contact/",
"currentStep": 0,
"fields": {
"fd8c0ce15f56440abee3358a9fe9c9d8": "Jane Doe"
}
}
------FormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="0c1e7d2b9a4f4c55b1f0a3c9d8e7f6a5_file_0"; filename="resume.pdf"
Content-Type: application/pdf
(binary data)
------FormBoundary7MA4YWxkTrZu0gW--Read the response
When the API saves the submission, it returns 200 OK with a result object:
- success – true when the API saved the submission.
- submissionKey – The key of the saved submission. Send it as submissionKey with the next step of a multi-step form.
- validationFail – false when the submission succeeds.
- messages – A list of messages about the result. Each message has a section, a message, and an identifier.
When the API cannot save the submission, it returns a problem details response instead:
- 400 Bad Request – The request is malformed, or server-side validation failed. For a validation failure, the errors property lists the messages by form element key.
- 401 Unauthorized – The request has no valid token.
- 403 Forbidden – The form is not published, access to the form is restricted, or the user cannot add to the submission in submissionKey.
- 404 Not Found – No form matches the key, or the form is deleted or expired.
Test the API with Swagger UI
Swagger UI displays the Forms API specification in the browser so you can test requests during development.
- Install the Swashbuckle.AspNetCore.SwaggerUI package:
dotnet add package Swashbuckle.AspNetCore.SwaggerUI- Add Swagger UI in Configure. The following code limits it to the Development environment:
if (env.IsDevelopment())
{
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/_forms/v1/docs/openapi.json", "Optimizely Forms API");
});
}- Run the site and open /swagger in a browser.
- To test the endpoints that require a token, click Authorize and paste an access token.