Internet Access
Use the Fetch API and InternetModule in a SPECS Lens to make HTTPS requests, call external APIs, download media, and check whether the internet is available.
- Snapchat: not supported
- SPECS: fully supported
- Camera Kit Web: not supported
- Camera Kit Mobile: not supported
- SnapchatNot supported
- SPECSFully supported
- Camera Kit WebNot supported
- Camera Kit MobileNot supported
SPECS offers APIs to access the internet, so a Lens can call external APIs, open WebSocket connections, download media, and more.
fetch and performHttpRequest are methods of InternetModule. Older Lenses called them on RemoteServiceModule, where they're now deprecated. On SPECS 27, call them on InternetModule.
InternetModule lets a Lens access the internet with http and https requests. It has two methods for these requests: fetch and performHttpRequest. In most cases, use fetch.
Insecure connections (http) require Experimental APIs. A Lens that uses them is fine for testing but can't be published. A Lens that uses secure connections (https) can be published.
Send HTTPS requests with the Fetch API
SPECS offers the standard Fetch API to make https requests on the open internet. The API follows the MDN Fetch API reference.
Fetch API prerequisites
You need Lens Studio 5.25 and a SPECS 27 device.
Send a request with fetch
To use the Fetch API, add an InternetModule asset to your project and assign it to the script input, as in the examples on this page.
The Fetch API only works in the Preview panel when the Lens runs as SPECS: set the panel's device menu to SPECS 27 (see Preview Lenses for SPECS). Otherwise every request returns 404.
To send a request, call the fetch method. For example:
- TypeScript
- JavaScript
@component
export class FetchExampleGET extends BaseScriptComponent {
@input internetModule: InternetModule;
// Method called when the script is awake
onAwake() {
this.fetchData();
}
async fetchData() {
let request = new Request('[YOUR URL]', {
method: 'GET',
});
let response = await this.internetModule.fetch(request);
if (response.status == 200) {
let text = await response.text();
// Handle response
}
}
}
//@input Asset.InternetModule internetModule
/** @type {InternetModule} */
var internetModule = script.internetModule;
let request = new Request('[YOUR URL]', {
method: 'GET',
});
let response = await internetModule.fetch(request);
if (response.status == 200) {
let text = await response.text();
// Handle response
}
Fetch can also send POST, PUT, and DELETE requests.
The following example sends a POST request with headers and parses the JSON response. It assumes a server that echoes the request body back under a json key (as httpbin.org/post does); adjust responseJson.json to the shape your server returns.
- TypeScript
- JavaScript
@component
export class FetchExamplePOST extends BaseScriptComponent {
@input internetModule: InternetModule;
onAwake() {
this.fetchData();
}
async fetchData() {
let request = new Request('[YOUR URL]', {
method: 'POST',
body: JSON.stringify({ user: { name: 'user', career: 'developer' } }),
headers: {
'Content-Type': 'application/json',
},
});
let response = await this.internetModule.fetch(request);
if (response.status != 200) {
print('Failure: response not successful');
return;
}
let contentTypeHeader = response.headers.get('Content-Type');
if (!contentTypeHeader.includes('application/json')) {
print('Failure: wrong content type in response');
return;
}
let responseJson = await response.json();
let username = responseJson.json['user']['name'];
let career = responseJson.json['user']['career'];
}
}
//@input Asset.InternetModule internetModule
/** @type {InternetModule} */
var internetModule = script.internetModule;
let request = new Request('[YOUR URL]', {
method: 'POST',
body: JSON.stringify({ user: { name: 'user', career: 'developer' } }),
headers: {
'Content-Type': 'application/json',
},
});
let response = await internetModule.fetch(request);
if (response.status != 200) {
print('Failure: response not successful');
return;
}
let contentTypeHeader = response.headers.get('content-type');
if (!contentTypeHeader.includes('application/json')) {
print('Failure: wrong content type in response');
return;
}
let responseJson = await response.json();
let username = responseJson.json['user']['name'];
let career = responseJson.json['user']['career'];
For a complete project that uses the Fetch API, see the Fetch sample on GitHub.
Fetch API compatibility on SPECS
The Fetch API on SPECS supports the methods in the standard, with the following exceptions:
-
The Request constructor doesn't take another Request as input; it only takes a URL.
-
Request and Response bodies can be read with
bytes,text, andjson. Response also hasblob; Request doesn't. ThebodyandarrayBufferproperties aren't supported yet. -
Other properties related to web browser functionality aren't supported. The following tables list the supported (✅) and unsupported (❌) members.
RequestResponseHeadersRequest(input, options)✅ Response()✅ Headers()✅ body❌ body❌ append()✅ bodyUsed✅ bodyUsed✅ delete()✅ cache❌ headers✅ entries()✅ credentials❌ ok✅ forEach()❌ destination❌ redirected❌ get()✅ headers✅ status✅ getSetCookie()❌ integrity❌ statusText✅ has()✅ isHistoryNavigation❌ type❌ keys()✅ keepalive❌ url✅ set()✅ method✅ arrayBuffer()❌ values()✅ mode❌ blob()✅ redirect✅ bytes()✅ referrer❌ clone()❌ referrerPolicy❌ formData()❌ signal❌ json()✅ url✅ text()✅ arrayBuffer()❌ blob()❌ bytes()✅ clone()❌ formData()❌ json()✅ text()✅
Send HTTPS requests with performHttpRequest
The performHttpRequest method of InternetModule also sends HTTPS requests.
performHttpRequest is a simpler API with less functionality, kept for compatibility. Use fetch instead where you can.
To use performHttpRequest, create a RemoteServiceHttpRequest, configure it, and send it with InternetModule. For example:
- TypeScript
- JavaScript
@component
export class GetCatFacts extends BaseScriptComponent {
@input
internetModule: InternetModule;
// Method called when the script is awake
onAwake() {
// Create a new HTTP request
let httpRequest = RemoteServiceHttpRequest.create();
httpRequest.url = 'https://catfact.ninja/facts'; // Set the URL for the request
httpRequest.method = RemoteServiceHttpRequest.HttpRequestMethod.Get; // Set the HTTP method to GET
// Perform the HTTP request
this.internetModule.performHttpRequest(httpRequest, (response) => {
if (response.statusCode === 200) {
// Check if the response status is 200 (OK)
print('Body: ' + response.body);
}
});
}
}
//@input Asset.InternetModule internetModule
/** @type {InternetModule} */
var internetModule = script.internetModule;
// Create a new HTTP request
let httpRequest = RemoteServiceHttpRequest.create();
httpRequest.url = 'https://catfact.ninja/facts'; // Set the URL for the request
httpRequest.method = RemoteServiceHttpRequest.HttpRequestMethod.Get; // Set the HTTP method to GET
// Perform the HTTP request
internetModule.performHttpRequest(httpRequest, (response) => {
if (response.statusCode === 200) {
// Check if the response status is 200 (OK)
print('Body: ' + response.body);
}
});
A RemoteServiceHttpRequest can send Get, Post, Put, Delete, and Patch requests (RemoteServiceHttpRequest.HttpRequestMethod). Set the request's url before you send it.
Set headers with setHeader(name, value). The following example uses request headers for authorization, where encodedCredentials is your Base64-encoded client ID and secret:
var httpRequest = RemoteServiceHttpRequest.create();
httpRequest.url = '[YOUR URL]';
httpRequest.method = RemoteServiceHttpRequest.HttpRequestMethod.Post;
httpRequest.setHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.setHeader('Authorization', `Basic ${encodedCredentials}`);
httpRequest.body = 'grant_type=client_credentials';
script.internetModule.performHttpRequest(httpRequest, function (response) {
print('Status code: ' + response.statusCode);
print('Content type: ' + response.contentType);
print('Body: ' + response.body);
print('Headers: ' + response.headers);
print('Header(date): ' + response.getHeader('date'));
print('Header(contenttype): ' + response.getHeader('content-type'));
});
Download remote media into a SPECS Lens
To download media (images, video, glTF, audio, and more), call makeResourceFromUrl on InternetModule to create a DynamicResource from the URL, then pass that resource to the matching method of RemoteMediaModule. For example:
Download an Image from a URL
- TypeScript
- JavaScript
@component
export class GetHttpImage extends BaseScriptComponent {
@input image: Image;
// Import the InternetModule and RemoteMediaModule
private internetModule: InternetModule = require('LensStudio:InternetModule');
private remoteMediaModule: RemoteMediaModule = require('LensStudio:RemoteMediaModule');
// URL of the image to fetch
private imageUrl: string = '[YOUR IMAGE URL]';
// Method called when the script is awake
onAwake() {
this.fetchImage();
}
fetchImage() {
if (!this.internetModule || !this.remoteMediaModule) {
print('Internet Module or Remote Media Module is missing.');
return;
}
try {
print('Fetching image...');
// Using makeResourceFromUrl to fetch the image
const resource: DynamicResource = this.internetModule.makeResourceFromUrl(
this.imageUrl
);
// Load resource and convert it to image texture
if (resource) {
this.remoteMediaModule.loadResourceAsImageTexture(
resource,
(texture) => {
// Assign texture to a material
print('Image texture loaded: ' + texture);
this.image.mainMaterial.mainPass.baseTex = texture;
},
(error) => {
print('Error loading image texture: ' + error); // Print an error message if loading fails
}
);
} else {
print('Error: Failed to create resource from URL.');
}
} catch (error) {
print('Error fetching image: ' + error);
}
}
}
//@input Component.Image image
// Import the InternetModule and RemoteMediaModule
var internetModule = require('LensStudio:InternetModule');
var remoteMediaModule = require('LensStudio:RemoteMediaModule');
// URL of the image to fetch
var imageUrl = '[YOUR IMAGE URL]';
// Initialize processing state
var isProcessing = false;
// Create and bind the OnStartEvent
script.createEvent('OnStartEvent').bind(onStart);
// Function that's called on starting the event
function onStart() {
if (isProcessing) {
print('A request is already in progress.');
return;
}
isProcessing = true;
fetchAndLoadImage();
}
// Function to fetch and load the image as a texture
function fetchAndLoadImage() {
if (!internetModule || !remoteMediaModule) {
print('InternetModule or RemoteMediaModule is not available.');
isProcessing = false;
return;
}
try {
print('Fetching image...');
// Create a resource from the image URL
var resource = internetModule.makeResourceFromUrl(imageUrl);
// Load resource and convert it to image texture
if (resource) {
remoteMediaModule.loadResourceAsImageTexture(
resource,
function (texture) {
// Image texture loaded successfully, apply texture
print('Image texture loaded: ' + texture);
script.image.mainMaterial.mainPass.baseTex = texture;
},
function (error) {
print('Error loading image texture: ' + error);
}
);
} else {
print('Error: Failed to create resource from URL.');
}
} catch (error) {
print('Error fetching image: ' + error);
} finally {
isProcessing = false;
}
}
Download a glTF with animations from a URL
- TypeScript
- JavaScript
@component
export class DownloadGltfExample extends BaseScriptComponent {
@input
material: Material;
@input
cameraObject: SceneObject;
private internetModule: InternetModule = require('LensStudio:InternetModule');
private remoteMediaModule: RemoteMediaModule = require('LensStudio:RemoteMediaModule');
onAwake() {
// Set the URL to your remote GLTF resource
let gltfUrl: string = 'YOUR_GLTF_URL_HERE';
if (!this.internetModule || !this.remoteMediaModule) {
print('Internet Module or Remote Media Module is missing.');
return;
}
try {
print('Fetching gltf asset...');
let resource: DynamicResource =
this.internetModule.makeResourceFromUrl(gltfUrl);
if (resource) {
this.remoteMediaModule.loadResourceAsGltfAsset(
resource,
(gltfAsset) => {
let gltfSettings = GltfSettings.create();
gltfSettings.convertMetersToCentimeters = true;
gltfAsset.tryInstantiateAsync(
this.sceneObject,
this.material,
(sceneObj) => {
// Get the camera position
let cameraPosition = this.cameraObject
.getTransform()
.getWorldPosition();
// Set the position of the instantiated GLTF object in front of the camera
sceneObj
.getTransform()
.setWorldPosition(
new vec3(
cameraPosition.x,
cameraPosition.y,
cameraPosition.z - 100
)
);
// Get the Animation Player component from second child of the object. Adjust it depending on where the Animation Player is in the gltf model.
let animationPlayer = sceneObj
.getChild(0)
.getChild(0)
.getComponent('AnimationPlayer');
print('Animation Player: ' + animationPlayer);
let activeClips = animationPlayer.getActiveClips();
let inactiveClips = animationPlayer.getInactiveClips();
print('Active Clips: ' + activeClips.length);
print('Inactive Clips: ' + inactiveClips.length);
inactiveClips.forEach((clip) => {
print('Inactive Clip: ' + clip);
});
animationPlayer.playClipAt('Talk', 0);
},
(error) => {
print('Error: ' + error);
},
(progress) => {
print('Progress: ' + progress);
},
gltfSettings
);
},
(error) => {
// Handle error if GLTF does not load
print('Error: ' + error);
}
);
} else {
print('Failed to create resource from URL.');
}
} catch (error) {
print('Error fetching gltf asset: ' + error);
}
}
}
//@input Asset.Material material
//@input SceneObject cameraObject
let internetModule = require('LensStudio:InternetModule');
let remoteMediaModule = require('LensStudio:RemoteMediaModule');
let gltfUrl = 'YOUR_GLTF_URL_HERE';
if (!internetModule || !remoteMediaModule) {
print('Internet Module or Remote Media Module is missing.');
return;
}
try {
print('Fetching GLTF asset from URL');
let resource = internetModule.makeResourceFromUrl(gltfUrl);
if (resource) {
remoteMediaModule.loadResourceAsGltfAsset(
resource,
(gltfAsset) => {
let gltfSettings = GltfSettings.create();
gltfSettings.convertMetersToCentimeters = true;
gltfAsset.tryInstantiateAsync(
script.sceneObject,
script.material,
(sceneObj) => {
// Get the camera position
let cameraPosition = script.cameraObject
.getTransform()
.getWorldPosition();
// Set the position of the instantiated GLTF object in front of the camera
sceneObj
.getTransform()
.setWorldPosition(
new vec3(
cameraPosition.x,
cameraPosition.y,
cameraPosition.z - 100
)
);
// Get the Animation Player component from second child of the object. Adjust it depending on where the Animation Player is in the gltf model.
let animationPlayer = sceneObj
.getChild(0)
.getChild(0)
.getComponent('Component.AnimationPlayer');
print('Animation Player: ' + animationPlayer);
let activeClips = animationPlayer.getActiveClips();
let inactiveClips = animationPlayer.getInactiveClips();
print('Active Clips: ' + activeClips.length);
print('Inactive Clips: ' + inactiveClips.length);
inactiveClips.forEach((clip) => {
print(clip);
});
animationPlayer.playClipAt('Idle', 0);
},
(error) => {
print('Error instantiating GLTF asset: ' + error);
},
(progress) => {
print('Progress: ' + progress);
},
gltfSettings
);
},
(error) => {
print('Error loading GLTF asset: ' + error);
}
);
} else {
print('Failed to create resource from URL.');
}
} catch (error) {
print('Error fetching gltf asset: ' + error);
}
RemoteMediaModule loads the following media types this way:
| Media type | Method | Returned class |
|---|---|---|
| Image | loadResourceAsImageTexture | Asset.Texture |
| Video | loadResourceAsVideoTexture | Asset.Texture |
| glTF | loadResourceAsGltfAsset | Asset.GltfAsset |
| Audio | loadResourceAsAudioTrackAsset | Asset.AudioTrackAsset |
| Text | loadResourceAsString | string |
| Raw bytes | loadResourceAsBytes | Uint8Array |
| Gaussian splat | loadResourceAsGaussianSplattingAsset | Asset.GaussianSplattingAsset |
| Runtime bundle | loadResourceAsRuntimeBundle | Asset |
Check internet availability on SPECS
On SPECS, a Lens can detect and respond to changes in internet availability. Use this to avoid frozen, empty, or broken experiences, and to tell the user when a feature needs the internet.
Internet availability prerequisites
You need Lens Studio 5.25 and a SPECS 27 device.
The isInternetAvailable method of DeviceInfoSystem checks the current state of the internet connection. It returns true if the internet is available and false if it isn't.
Call isInternetAvailable when the Lens starts to find the initial state of the connection, or at any later time.
onInternetStatusChanged is an event of DeviceInfoSystem that fires whenever the internet connection status changes, so the Lens can respond to changes in connectivity.
Features such as Speech-to-Text (ASR), Connected Lenses, Bitmoji Module, Location Cloud Storage, Map, Remote Service Gateway, and Snap Cloud require an internet connection.
- TypeScript
- JavaScript
@component
export class NewScript extends BaseScriptComponent {
@input textObject: Text;
onAwake() {
this.textObject.text = global.deviceInfoSystem.isInternetAvailable()
? 'Internet is available'
: 'No internet';
global.deviceInfoSystem.onInternetStatusChanged.add((args) => {
this.textObject.text = args.isInternetAvailable
? 'UPDATED: Internet is available'
: 'UPDATED: No internet';
});
}
}
// @input Component.Text textObject
script.textObject.text = global.deviceInfoSystem.isInternetAvailable()
? 'Internet is available'
: 'No internet';
global.deviceInfoSystem.onInternetStatusChanged.add(function (eventData) {
script.textObject.text = eventData.isInternetAvailable
? 'UPDATED: Internet is available'
: 'UPDATED: No internet';
});