Skip to main content
Platform
Camera Kit

Calling HTTP Endpoints From a Lens

Overview

HTTP requests let lenses contact APIs directly, enabling dynamic content and real-time interactivity. Unlike Remote API calls, which rely on a custom processor written by partners, this feature requires minimal app-side setup. This guide introduces the HTTP request feature in Camera Kit and explains how to configure and use it effectively. You'll learn:

  • What is required to use this feature
  • How to make the necessary changes in your lens
  • How to configure URL allowlisting in the My Lenses Portal
  • Changes in your Camera Kit app and when they are needed
  • Common ways to authenticate HTTP Endpoints

Prerequisites

To enable HTTP requests in your Camera Kit lenses, ensure:

  • Camera Kit Credentials: API token and access to the My Lenses portal. See the Getting Started guide if you're new to Camera Kit.
  • Lens Studio: Version 5.4 or later.
  • Camera Kit SDKs: Android/iOS SDKs 1.37 or Web SDK 1.1.0 or later.
  • API Endpoint: An accessible API that uses HTTPS.

Lens: Perform HTTP Request

Before diving into the steps, you can try an existing lens project that already includes everything and displays a random cat fact on the screen: ​​cat-fact-lens-project.zip. This allows you to see the functionality in action and better understand the process.

​​For this guide, we will use the catfact.ninja API as an example to demonstrate how to perform an HTTP request. This API provides a random cat fact, which will be displayed in the Logger window. Note: During development, Lens Studio skips endpoint verification. For Camera Kit apps, you'll need to configure the endpoint in the My Lenses Portal. See the next section for details.

If you'd prefer a visual walkthrough of the steps how to implement it yourself, watch the video below:

If you prefer step-by-step written instructions, follow the guide below:

  1. Ensure "Camera Kit" is enabled in the Project Settings.
  2. In the Asset Browser, include "Internet Module" service.
  3. Create a Script which performs HTTP request
// @input Asset.InternetModule serviceModule

const req = RemoteServiceHttpRequest.create();
req.url = 'https://catfact.ninja/fact';
req.method = RemoteServiceHttpRequest.HttpRequestMethod.Get;

script.serviceModule.performHttpRequest(req, (res) => {
if (res.statusCode === 200) {
print(res.body);
} else if (res.statusCode === 400 && res.headers['x-camera-kit-error-type']) {
print(`Error: ${res.body}`);
} else {
print(`Error: Unexpected HTTP status code ${res.statusCode}.`);
}
});
  1. Drag the script to the Scene Hierarchy window and connect to the recently added "Internet Module".
  2. Ensure the lens prints a random cat fact in the Logger window.

Notes

Handling non-HTTP errors

The code above has a special check for the x-camera-kit-error-type response header. This header reflects errors originating on the Camera Kit side and has three possible values:

  1. RequestValidationError: These errors are triggered when a request is not allowlisted. The request body will contain a string with a detailed error message in this case.
  2. LensHttpHandlerError: This error occurs when code provided by a partner to enhance lens HTTP requests throws an exception.
  3. UnknownError: Any other error originating in the Camera Kit SDK that doesn't fall into the categories above.

HTTP response headers

Only a subset of response headers is provided to the lens:

  • Accept-Ranges
  • Cache-Control
  • Content-Language
  • Content-Length
  • Content-Type
  • Date
  • ETag
  • Expires
  • Last-Modified
  • Location

My Lenses Portal: Configure Allowlist

Lens Studio bypasses endpoint verification for HTTP requests during development to enhance efficiency. However, in Camera Kit, all HTTP requests are validated against an allowlist to ensure security and compliance. This prevents unauthorized access and ensures adherence to data policies.

If you'd prefer a visual walkthrough of the steps how to configure an allowlist, watch the video below. It provides a detailed demonstration of how to configure the allowlist in My Lenses Portal.

For those who prefer step-by-step written instructions, follow the guide below:

  1. Access the portal: https://my-lenses.snapchat.com/apis.
  2. Click "+ Add API"
  3. Specify the API host and endpoints. An endpoint preview field will show an URL that is allowed to be called by the lens.
  4. Select "Provided Processor" to tell Camera Kit to use a built-in HTTP processor.
  5. Provide your "Snap Kit App ID". You can get that from the Developer Portal by:
    • Going to My Lenses Portal: https://my-lenses.snapchat.com.
    • Clicking "Apps".
    • Clicking on your Snap Kit App in the list.
    • Clicking on the "Developer Portal" button.
    • Copying the ID of your app under the app title.
  6. Save the API configuration

Notes

When you run your Camera Kit app, you specify an API token that is associated with a Snap Kit app. Camera Kit uses this Snap Kit app to determine the URL allowlist associated with it. Therefore, each allowlist must include the Snap Kit App ID field value.

Camera Kit App: Advanced Use-Cases

Changes on the Camera Kit app side are needed for advanced use cases such as HTTP endpoint authentication or logging to troubleshoot issues.

Web SDK

Below is an example of adding a bearer token to HTTP requests initiated by the lens and logging each request to browser console:

const customLensHttpHandler: LensHttpHandler = async (url, init, lensRequest) => {
// Add an authentication token to the headers
const sessionToken = await getAuthToken();
const updatedInit = {
...init,
headers: {
...init.headers,
'Authorization': `Bearer ${sessionToken}`,
},
};

// Log the request details for debugging
console.log(`Requesting ${lensRequest.url} from lens: ${lensRequest.lens.name}`);

// Use fetch to perform the HTTP request
return fetch(url, updatedInit);
};

const cameraKit = bootstrapCameraKit({
apiToken,
lensHttpHandler: customLensHttpHandler,
});

Android SDK

configureLenses {
// Configure a custom HTTP handler to modify requests before they are sent
configureHttpHandler { configuration ->
val defaultHandler = configuration.httpHandler
configuration.httpHandler = LensesComponent.HttpHandler { request, onResponse ->
// Fetch the authentication token
val sessionToken = getAuthToken()

// Add the authentication token to the headers
val updatedHeaders = request.headers.toMutableMap().apply {
this["Authorization"] = "Bearer $sessionToken"
}

// Create an updated request with the new headers
val updatedRequest = LensesComponent.HttpHandler.Request(
request.id,
request.lensId,
request.url,
request.method,
request.body,
updatedHeaders
)

// Log the request details
Log.d("CustomLensHttpHandler", "Requesting ${request.url} from lens: ${request.lensId}")

// Pass the updated request to the default handler
defaultHandler.apply(updatedRequest, onResponse)
}
}
}

iOS SDK

class CustomLensHttpHandler: NSObject, LensHttpHandler {
func perform(_ lensHttpRequest: LensHttpRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
Task {
do {
let token = try await getAuthToken()

// Create a mutable copy of the original request
guard let mutableRequest = (lensHttpRequest.urlRequest as NSURLRequest).mutableCopy() as? NSMutableURLRequest else {
throw NSError(domain: "RequestError", code: 400, userInfo: [NSLocalizedDescriptionKey: "Failed to create mutable request"])
}

// Add the Authorization header
mutableRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

// Log the request details
print("Requesting \(lensHttpRequest.urlRequest.url?.absoluteString ?? "unknown URL") from lens: \(lensHttpRequest.lensId)")

// Perform the HTTP request
let (data, response) = try await URLSession.shared.data(for: mutableRequest as URLRequest)

// Call the completion handler with the response
completion(data, response, nil)
} catch {
// Call the completion handler with the error
completion(nil, nil, error)
}
}
}
}

let dataProviderComponent = DataProviderComponent(
// ...
lensHttpHandler: CustomLensHttpHandler()
)

Common Ways to Authenticate HTTP Endpoints

Authentication is critical for securing HTTP endpoints and ensuring only authorized requests are processed. The following are two common methods.

Bearer Token Authentication

Most APIs use bearer tokens for authentication, which must be included in the HTTP request headers.

Recommended Practices:

  1. Do not hardcode tokens into the lens as they can be extracted by malicious parties.
  2. Instead, use the custom Lens HTTP handler on the Camera Kit side to inject tokens securely.
  3. Alternatively, supply the token as launch data so the lens script can dynamically add it to the request headers.

For web-based apps, cookies from an active web session may need to be included in the HTTP request.

Recommended Practices:

  1. Avoid storing or managing sensitive cookies directly in the lens script.
  2. Use the Lens HTTP handler to attach cookies securely from the Camera Kit app side.

Example:

const customLensHttpHandler: LensHttpHandler = (url, init) => {
// Add cookies of current web session
const updatedInit: RequestInit = {
...init,
credentials: "include",
};
return fetch(url, updatedInit);
};
Was this page helpful?
Yes
No