### Install Dependencies Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-developer-credentials/README.md Install the necessary packages for using developer credentials. ```bash npm install @esri/arcgis-rest-request npm install @esri/arcgis-rest-developer-credentials ``` -------------------------------- ### Install Dependencies Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Install Dependencies Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-geocoding/README.md Before using the geocoding utilities, install the necessary packages. ```bash npm install @esri/arcgis-rest-request npm install @esri/arcgis-rest-geocoding ``` -------------------------------- ### Install Dependencies Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-places/README.md Install the necessary packages for using @esri/arcgis-rest-places. ```bash npm install @esri/arcgis-rest-request npm install @esri/arcgis-rest-places ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/esri/arcgis-rest-js/blob/main/README.md Install project dependencies and perform an initial build. This command is typically run after cloning the repository. ```bash npm install && npm run build ``` -------------------------------- ### Access Development Environment Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Open this URL in your browser to access the development environment after starting the servers. ```bash https://localhost:8080/workspace/sample.html ``` -------------------------------- ### Install Dependencies Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-feature-service/README.md Install the necessary packages for using the @esri/arcgis-rest-feature-service module. ```bash npm install @esri/arcgis-rest-request npm install @esri/arcgis-rest-feature-service ``` -------------------------------- ### Run Development Server (Bundled) Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Start the development server for browser-based development. This command should be run in one terminal. ```bash npm run dev:bundled ``` -------------------------------- ### Serve Development Files Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Serve the development files. This command should be run in a separate terminal after starting the development server. ```bash npm run serve ``` -------------------------------- ### Install @esri/arcgis-rest-request Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-request/README.md Install the package using npm. This is the first step before you can use the request functionality. ```bash npm install @esri/arcgis-rest-request ``` -------------------------------- ### Install @esri/arcgis-rest-demographics Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-demographics/README.md Install the necessary packages for using demographics helpers. ```bash npm install @esri/arcgis-rest-request npm install @esri/arcgis-rest-demographics ``` -------------------------------- ### Install @esri/arcgis-rest-portal Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-portal/README.md Install the necessary packages for using the @esri/arcgis-rest-portal module. This includes the core request library and the portal module itself. ```bash npm install @esri/arcgis-rest-request npm install @esri/arcgis-rest-portal ``` -------------------------------- ### Install @esri/arcgis-rest-elevation Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-elevation/README.md Install the necessary packages for using the ArcGIS Elevation service. ```bash npm install @esri/arcgis-rest-request npm install @esri/arcgis-rest-elevation ``` -------------------------------- ### Install @esri/arcgis-rest-routing Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-routing/README.md Install the necessary packages for routing functionality. This includes the core request library, common utilities, and the routing package itself. ```bash npm install @esri/arcgis-rest-request npm install @esri/arcgis-rest-common npm install @esri/arcgis-rest-routing ``` -------------------------------- ### Run Development Server (ESM) Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Start the development server for Node.js development using ES Modules. This command should be run in one terminal. ```bash npm run dev:esm ``` -------------------------------- ### Get Place Details Source: https://context7.com/esri/arcgis-rest-js/llms.txt Fetches full details for a single place using its place ID. Allows requesting specific fields like name, address, and contact information. Requires authentication. ```typescript import { findPlacesNearPoint, getPlaceDetails } from "@esri/arcgis-rest-places"; import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK••••"); const search = await findPlacesNearPoint({ x: -0.1276, y: 51.5074, radius: 500, authentication: auth }); const placeId = search.results[0].placeId; const details = await getPlaceDetails({ placeId, requestedFields: ["place.name", "address.streetAddress", "contactInfo.telephone", "rating.user"], authentication: auth }); console.log(details.place.name); console.log(details.address?.streetAddress); console.log(details.contactInfo?.telephone); console.log(details.rating?.user); ``` -------------------------------- ### Watch TypeScript Files (Node.js) Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Continuously compile and watch TypeScript files for changes in a Node.js environment. This command should be run in a separate terminal after starting the ESM development server. ```bash npx tsx watch ./workspace/sample.ts ``` -------------------------------- ### Generic ArcGIS REST HTTP Call with @esri/arcgis-rest-js Source: https://context7.com/esri/arcgis-rest-js/llms.txt Demonstrates making anonymous GET requests, authenticated POST requests with query parameters using ApiKeyManager, and requesting raw GeoJSON format. Ensure proper error handling for requests. ```typescript import { request, ArcGISRequestError } from "@esri/arcgis-rest-request"; // Anonymous GET request – returns parsed JSON request("https://www.arcgis.com/sharing/rest", { httpMethod: "GET" }) .then((res) => console.log(res.currentVersion)); // e.g. 5.2 // Authenticated POST with query parameters import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK..."); request("https://www.arcgis.com/sharing/rest/search", { authentication: auth, params: { q: "parks AND type:Feature Service", num: 5 } }) .then((res) => console.log(`Found ${res.total} results`)) .catch((err: ArcGISRequestError) => { console.error(`${err.name} [${err.code}]: ${err.message}`); }); // Return raw GeoJSON format request("https://services.arcgis.com/.../FeatureServer/0/query", { params: { where: "1=1", outFields: "*", f: "geojson" } }).then((fc) => console.log(fc.type)); // "FeatureCollection" ``` -------------------------------- ### Search for Items using ArcGIS REST JS Source: https://github.com/esri/arcgis-rest-js/blob/main/workspace/sample.html Use the `searchItems` function to find items in your ArcGIS organization. This example searches for items related to 'water'. ```javascript import { searchItems } from "@esri/arcgis-rest-portal"; let element = document.createElement("pre"); document.body.appendChild(element); searchItems("water").then((response) => { element.textContent = JSON.stringify(response, null, 2); }); ``` -------------------------------- ### Make a Request to ArcGIS REST API Source: https://github.com/esri/arcgis-rest-js/blob/main/README.md Use the `request` function to make a GET request to an ArcGIS REST API endpoint. The response will be the JSON data from the item. ```javascript import { request } from "@esri/arcgis-rest-request"; const url = "https://www.arcgis.com/sharing/rest/content/items/6e03e8c26aad4b9c92a87c1063ddb0e3/data"; request(url).then((response) => { console.log(response); // WebMap JSON }); ``` -------------------------------- ### Get Available Data Collections Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-demographics/README.md Use this function to retrieve a list of available demographic data collections. You can optionally specify a country code to filter the results. ```javascript import { getAvailableDataCollections } from "@esri/arcgis-rest-demographics"; getAvailableDataCollections().then((response) => { response.DataCollections; // => [{ dataCollectionId: "KeyGlobalFacts", metadata: { ... }, data: [ ... ] }, ... ] }); ``` -------------------------------- ### request — Generic ArcGIS REST HTTP call Source: https://context7.com/esri/arcgis-rest-js/llms.txt The foundation of every package. Automatically selects GET or POST depending on URL length, encodes parameters as form data or query strings, injects tokens, and parses ArcGIS-flavored error bodies into typed ArcGISRequestError / ArcGISAuthError exceptions. Supports GeoJSON, HTML, text, and blob response formats in addition to the default JSON. ```APIDOC ## `request` — Generic ArcGIS REST HTTP call ### Description The foundation of every package. Automatically selects GET or POST depending on URL length, encodes parameters as form data or query strings, injects tokens, and parses ArcGIS-flavored error bodies into typed `ArcGISRequestError` / `ArcGISAuthError` exceptions. Supports GeoJSON, HTML, text, and blob response formats in addition to the default JSON. ### Method GET or POST (automatically determined) ### Endpoint Dynamic based on URL ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Optional - Parameters to be sent with the request. - **httpMethod** (string) - Optional - Explicitly set the HTTP method (e.g., 'GET', 'POST'). - **authentication** (IAuthenticationManager) - Optional - An authentication manager instance. - **responseType** (string) - Optional - The desired response format (e.g., 'json', 'geojson', 'html', 'text', 'blob'). ### Request Example ```javascript import { request, ArcGISRequestError } from "@esri/arcgis-rest-request"; // Anonymous GET request – returns parsed JSON request("https://www.arcgis.com/sharing/rest", { httpMethod: "GET" }) .then((res) => console.log(res.currentVersion)); // e.g. 5.2 // Authenticated POST with query parameters import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK..."); request("https://www.arcgis.com/sharing/rest/search", { authentication: auth, params: { q: "parks AND type:Feature Service", num: 5 } }) .then((res) => console.log(`Found ${res.total} results`)) .catch((err: ArcGISRequestError) => { console.error(`${err.name} [${err.code}]: ${err.message}`); }); // Return raw GeoJSON format request("https://services.arcgis.com/.../FeatureServer/0/query", { params: { where: "1=1", outFields: "*", f: "geojson" } }).then((fc) => console.log(fc.type)); // "FeatureCollection" ``` ### Response #### Success Response - **response** (any) - The parsed response from the ArcGIS REST API, format depends on `responseType`. ``` -------------------------------- ### Generate API Documentation Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Generate the API reference documentation using TypeDoc. This command uses the configuration specified in `typedoc.json`. ```bash npm run typedoc ``` -------------------------------- ### Review Release Changes Source: https://github.com/esri/arcgis-rest-js/blob/main/RELEASE.md Run this command to display a diff of what will be committed to master before publishing. This is part of the v3 release process. ```bash npm run release:review ``` -------------------------------- ### Prepare Release: Bump Versions and Update Changelog Source: https://github.com/esri/arcgis-rest-js/blob/main/RELEASE.md Use this command to bump the version in individual package.json files and parse commit messages to update the changelog. This is a step in the v3 release process. ```bash npm run release:prepare ``` -------------------------------- ### Run All Tests Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Execute the comprehensive test suite for the arcgis-rest-js project using Vitest. ```bash npm test ``` -------------------------------- ### Get an ArcGIS Item Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-portal/README.md Use the getItem function to retrieve details about a specific ArcGIS item using its ID. The response includes properties like the item's title. ```javascript import { getItem } from "@esri/arcgis-rest-portal"; const itemId = "30e5fe3149c34df1ba922e6f5bbf808f"; getItem(itemId).then((response) => { console.log(response.title); // World Topographic Map }); ``` -------------------------------- ### Create an API Key Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-developer-credentials/README.md Use the `createApiKey` function to register a new API key with specified privileges and tags. Requires an authenticated session. ```javascript import { createApiKey, Privileges } from "@esri/arcgis-rest-developer-credentials"; const authSession: ArcGISIdentityManager = await ArcGISIdentityManager.signIn({ username: "xyz_usrName", password: "xyz_pw" }); createApiKey({ title: "xyz_title", description: "xyz_desc", tags: ["xyz_tag1", "xyz_tag2"], privileges: [Privileges.Geocode, Privileges.FeatureReport], authentication: authSession }) .then((registeredAPIKey) => { // => {apiKey: "xyz_key", item: {tags: ["xyz_tag1", "xyz_tag2"], ...}, ...} }) .catch((e) => { // => an exception object }); ``` -------------------------------- ### Publish Release: Increment Root Version, Push Tag, and Publish Packages Source: https://github.com/esri/arcgis-rest-js/blob/main/RELEASE.md This command increments the version in the root package.json, pushes a new tag to GitHub, and publishes each individual package to npm. Be prepared to enter GitHub credentials, especially if using MFA. This is the final step in the v3 release process. ```bash npm run release:publish ``` -------------------------------- ### suggest Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-geocoding/README.md Provides location suggestions based on a partial input string. ```APIDOC ## suggest ### Description Provides location suggestions based on a partial input string. ### Method Signature `suggest(input: string, options?: any): Promise` ### Parameters - **input** (string) - Required - The partial input string for which to get suggestions. - **options** (any) - Optional - Additional options for the suggestion request. ### Request Example ```javascript import { suggest } from "@esri/arcgis-rest-geocoding"; suggest("Starb").then((response) => { console.log(response.suggestions); }); ``` ### Response #### Success Response - **suggestions** (array) - An array of suggested locations. ``` -------------------------------- ### Clone Repository Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Clone the arcgis-rest-js repository to your local machine. ```bash git clone git@github.com:Esri/arcgis-rest-js.git ``` -------------------------------- ### suggest: Geocoding Autocomplete Suggestions Source: https://context7.com/esri/arcgis-rest-js/llms.txt Provides ranked text suggestions for partial search strings to build autocomplete UIs. Pairs with `geocode` using the returned `magicKey` to resolve full addresses efficiently without consuming geocoding credits per keypress. ```typescript import { suggest, geocode } from "@esri/arcgis-rest-geocoding"; suggest("Starb") .then((res) => { console.log(res.suggestions[0].text); // "Starbucks" // Use the magicKey to resolve the full address efficiently return geocode({ singleLine: res.suggestions[0].text, magicKey: res.suggestions[0].magicKey }); }) .then((res) => console.log(res.candidates[0].location)); // => { x: ..., y: ..., spatialReference: { wkid: 4326 } } ``` -------------------------------- ### Watch Local Source Changes Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Run these commands in the root of the repository to automatically recompile packages when TypeScript source changes. Useful for local development and testing. ```bash # watch 'request' and rebuild a UMD for the browser npm run dev:bundled ``` ```bash # rebuild ES6 files npm run dev:esm ``` ```bash # rebuild CommonJS npm run dev:cjs ``` ```bash # watch all the packages npm run dev ``` -------------------------------- ### Run Tests in Chrome with Debugging Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Run tests in Chrome and watch for changes. This opens a Chrome window where you can inspect test information and use the debugger. ```bash npm run test:chrome:debug ``` -------------------------------- ### suggest Source: https://context7.com/esri/arcgis-rest-js/llms.txt Provides geocoding autocomplete by returning ranked text suggestions for a partial search string. It can be paired with `geocode` using a `magicKey` for efficient address resolution. ```APIDOC ## `suggest` — Geocoding autocomplete Returns ranked text suggestions for a partial search string. Pairs with `geocode` (using the returned `magicKey`) to build autocomplete UIs without consuming geocoding credits for each keypress. ```ts import { suggest, geocode } from "@esri/arcgis-rest-geocoding"; suggest("Starb") .then((res) => { console.log(res.suggestions[0].text); // "Starbucks" // Use the magicKey to resolve the full address efficiently return geocode({ singleLine: res.suggestions[0].text, magicKey: res.suggestions[0].magicKey }); }) .then((res) => console.log(res.candidates[0].location)); // => { x: ..., y: ..., spatialReference: { wkid: 4326 } } ``` ``` -------------------------------- ### API Key Authentication with @esri/arcgis-rest-js Source: https://context7.com/esri/arcgis-rest-js/llms.txt Shows how to create an ApiKeyManager from a key string, persist it to local storage, restore it, and use it for authenticated requests like geocoding. This manager wraps a static ArcGIS API key. ```typescript import { ApiKeyManager } from "@esri/arcgis-rest-request"; // Create from a key string const auth = ApiKeyManager.fromKey("AAPK••••••••••••••••••••••••••••••"); // Persist to storage localStorage.setItem("auth", auth.serialize()); // Restore later const restored = ApiKeyManager.deserialize(localStorage.getItem("auth")!); // Pass to any request function import { geocode } from "@esri/arcgis-rest-geocoding"; geocode({ singleLine: "Eiffel Tower", authentication: restored }) .then((res) => console.log(res.candidates[0].location)); // => { x: 2.2945, y: 48.8584, spatialReference: { wkid: 4326 } } ``` -------------------------------- ### createApiKey Source: https://context7.com/esri/arcgis-rest-js/llms.txt Creates a new ArcGIS API key item in a user's portal content, registers it as an application, and optionally generates an initial access token with configurable expiration and privilege scopes. ```APIDOC ## `createApiKey` — Register a new developer API key Creates a new ArcGIS API key item in a user's portal content, registers it as an application, and optionally generates an initial access token with configurable expiration and privilege scopes. ```ts import { createApiKey } from "@esri/arcgis-rest-developer-credentials"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; const session = await ArcGISIdentityManager.signIn({ username: "jane", password: "••••" }); const expiry = new Date(); expiry.setDate(expiry.getDate() + 30); createApiKey({ title: "My App Key", description: "Key for the field survey app", tags: ["survey", "mobile"], privileges: [ "premium:user:networkanalysis:routing", "premium:user:geocode:stored" ], generateToken1: true, apiToken1ExpirationDate: expiry, authentication: session }).then((key) => { console.log(key.accessToken1); // "AAPK••••" – the usable API key string console.log(key.item.id); // portal item ID console.log(key.item.tags); // ["survey", "mobile"] }); ``` ``` -------------------------------- ### Register a New API Key with `createApiKey` Source: https://context7.com/esri/arcgis-rest-js/llms.txt Creates a new ArcGIS API key item, registers it as an application, and optionally generates an initial access token with configurable expiration and privilege scopes. Requires authentication. ```typescript import { createApiKey } from "@esri/arcgis-rest-developer-credentials"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; const session = await ArcGISIdentityManager.signIn({ username: "jane", password: "••••" }); const expiry = new Date(); expiry.setDate(expiry.getDate() + 30); createApiKey({ title: "My App Key", description: "Key for the field survey app", tags: ["survey", "mobile"], privileges: [ "premium:user:networkanalysis:routing", "premium:user:geocode:stored" ], generateToken1: true, apiToken1ExpirationDate: expiry, authentication: session }).then((key) => { console.log(key.accessToken1); // \"AAPK••••\" – the usable API key string console.log(key.item.id); // portal item ID console.log(key.item.tags); // ["survey", "mobile"] }); ``` -------------------------------- ### Create a Portal Group with `createGroup` Source: https://context7.com/esri/arcgis-rest-js/llms.txt Creates a new group in an ArcGIS Online or Enterprise organization. The authenticated user becomes the group owner. Requires authentication. ```typescript import { createGroup } from "@esri/arcgis-rest-portal"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; const session = await ArcGISIdentityManager.signIn({ username: "jane", password: "••••" }); createGroup({ group: { title: "Field Survey Team", access: "org", // \"private\" | \"org\" | \"public\" description: "Internal group for field data collection workflows", tags: ["field", "survey", "mobile"], membershipAccess: "org" }, authentication: session }).then((res) => { console.log(res.success); // true console.log(res.group.id); // new group's ID }); ``` -------------------------------- ### Run Node Tests with Debugging Source: https://github.com/esri/arcgis-rest-js/blob/main/CONTRIBUTING.md Run Node.js tests and automatically open the Chrome debugger (version 60+). This is useful for debugging tests during development. ```bash npm run test:node:debug ``` -------------------------------- ### Find Elevation at a Point using JavaScript Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-elevation/README.md Use the `findElevationAtPoint` function to retrieve elevation data for a specific geographic point. Ensure you provide a valid access token for authentication. ```javascript import { findElevationAtPoint } from "@esri/arcgis-rest-elevation"; import { ApiKeyManager } from "@esri/arcgis-rest-request"; const response = await findElevationAtPoint({ lon: -179.99, lat: -85.05, authentication: ApiKeyManager.fromKey("YOUR_ACCESS_TOKEN"); }); console.log(response.result.point.z) ``` -------------------------------- ### getPlaceDetails Source: https://context7.com/esri/arcgis-rest-js/llms.txt Fetches full details for a single place, including contact info, address, and rating, given a `placeId`. ```APIDOC ## `getPlaceDetails` — Place details Fetches full details for a single place — contact info, address, price range, rating, opening hours — given a `placeId` returned by a places search. ### Parameters - `placeId`: The unique identifier for the place. - `requestedFields`: Array of strings specifying which fields to retrieve. - `authentication`: Authentication object for accessing the service. ### Request Example ```javascript import { findPlacesNearPoint, getPlaceDetails } from "@esri/arcgis-rest-places"; import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK••••"); const search = await findPlacesNearPoint({ x: -0.1276, y: 51.5074, radius: 500, authentication: auth }); const placeId = search.results[0].placeId; const details = await getPlaceDetails({ placeId, requestedFields: ["place.name", "address.streetAddress", "contactInfo.telephone", "rating.user"], authentication: auth }); console.log(details.place.name); console.log(details.address?.streetAddress); console.log(details.contactInfo?.telephone); console.log(details.rating?.user); ``` ### Response - `place`: Object containing general place information. - `address`: Object containing address details. - `contactInfo`: Object containing contact information. - `rating`: Object containing rating details. ``` -------------------------------- ### Generate Types from OpenAPI Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-places/README.md Generate TypeScript types from the OpenAPI definition for the places service. This is useful for maintaining type safety in your application. ```bash npx openapi-typescript@5 https://places-api.arcgis.com/arcgis/rest/services/places-service/v1/specification/open-api-v3-0/ --output packages/arcgis-rest-places/src/openapi-types.ts ``` -------------------------------- ### applyEdits Source: https://context7.com/esri/arcgis-rest-js/llms.txt Atomically applies adds, updates, and deletes to a hosted feature layer in a single request. Supports global IDs and attachment operations. ```APIDOC ## `applyEdits` — Add, update, and delete features Atomically applies adds, updates, and deletes to a hosted feature layer in a single request. Supports global IDs and attachment operations. ```ts import { applyEdits } from "@esri/arcgis-rest-feature-service"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; const session = await ArcGISIdentityManager.signIn({ username: "jane", password: "••••" }); applyEdits({ url: "https://services.arcgis.com/.../FeatureServer/0", authentication: session, adds: [ { geometry: { x: -117.1956, y: 34.0572, spatialReference: { wkid: 4326 } }, attributes: { name: "New Park", status: "open" } } ], updates: [ { attributes: { OBJECTID: 42, status: "closed" } } ], deletes: [101, 202] }).then((res) => { console.log(res.addResults); // [{ objectId: 999, success: true }] console.log(res.updateResults); // [{ objectId: 42, success: true }] console.log(res.deleteResults); // [{ objectId: 101, success: true }, ...] }); ``` ``` -------------------------------- ### Find Elevation at Multiple Points Source: https://context7.com/esri/arcgis-rest-js/llms.txt Performs a batch lookup of surface elevations for an array of WGS 84 coordinates. The coordinate bounding box must not exceed 50 km. Requires authentication. ```typescript import { findElevationAtManyPoints } from "@esri/arcgis-rest-elevation"; import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK••••"); const results = await findElevationAtManyPoints({ // Each inner array: [longitude, latitude] coordinates: [ [31.1342, 29.9792], // Great Pyramid of Giza [31.1309, 29.9761], [31.1284, 29.9725] ], relativeTo: "meanSeaLevel", // or "ellipsoid" authentication: auth }); results.result.points.forEach((pt) => { console.log(`[${pt.coordinates}] → ${pt.elevation} m`); }); ``` -------------------------------- ### Application Credentials Authentication with @esri/arcgis-rest-js Source: https://context7.com/esri/arcgis-rest-js/llms.txt Demonstrates using ApplicationCredentialsManager for server-side applications to authenticate as an application using Client ID and Client Secret. It automatically handles token fetching and refreshing. ```typescript import { ApplicationCredentialsManager } from "@esri/arcgis-rest-request"; const session = ApplicationCredentialsManager.fromCredentials({ clientId: "abc123", clientSecret: "s3cr3t", // optional: point at an ArcGIS Enterprise portal portal: "https://myorg.maps.arcgis.com/sharing/rest", duration: 120 // token lifetime in minutes }); // Use with any request import { searchItems } from "@esri/arcgis-rest-portal"; searchItems({ q: "owner:esri", authentication: session }) .then((res) => res.results.forEach((item) => console.log(item.title))); ``` -------------------------------- ### getItem Source: https://context7.com/esri/arcgis-rest-js/llms.txt Retrieves metadata for any ArcGIS Online or Enterprise portal item by its item ID. Automatically decorates `thumbnailUrl` with an authenticated URL if applicable. ```APIDOC ## `getItem` — Fetch a portal item Retrieves metadata for any ArcGIS Online or Enterprise portal item by its item ID. Automatically decorates the `thumbnailUrl` property with an authenticated URL when an auth manager is provided and the item is not public. ### Parameters - `itemId`: The ID of the portal item. - `options`: Optional object containing parameters like `authentication`. - `authentication`: Authentication object for accessing the service. ### Request Example ```javascript import { getItem } from "@esri/arcgis-rest-portal"; import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK••••"); getItem("6e03e8c26aad4b9c92a87c1063ddb0e3", { authentication: auth }) .then((item) => { console.log(item.title); // "World Time Zones" console.log(item.type); // "Feature Service" console.log(item.thumbnailUrl); // fully qualified authenticated URL console.log(item.tags); }); ``` ### Response - `title`: The title of the item. - `type`: The type of the item (e.g., "Feature Service"). - `thumbnailUrl`: The URL for the item's thumbnail. - `tags`: An array of tags associated with the item. ``` -------------------------------- ### Manage Basemap Style Sessions with `BasemapStyleSession` Source: https://context7.com/esri/arcgis-rest-js/llms.txt Manages authenticated, time-limited sessions for the ArcGIS Basemap Styles service. Automatically renews the session token before expiry. Requires an API key for authentication. ```typescript import { BasemapStyleSession } from "@esri/arcgis-rest-basemap-sessions"; import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK••••"); const session = await BasemapStyleSession.start({ authentication: auth, // Optional: override the default basemap style session endpoint // startSessionUrl: "https://basemapstyles-api.arcgis.com/arcgis/rest/services/styles/v2/styles/shared-session" }); // session.token is a short-lived session token for map tile requests console.log(session.token); console.log(session.expires); // Date when the token expires // The session automatically refreshes; use session.token in tile URLs const tileUrl = `https://basemapstyles-api.arcgis.com/.../tiles/...?token=${session.token}`; ``` -------------------------------- ### Fetch Portal Item Metadata Source: https://context7.com/esri/arcgis-rest-js/llms.txt Retrieves metadata for an ArcGIS Online or Enterprise portal item using its ID. Automatically decorates `thumbnailUrl` with an authenticated URL if authentication is provided and the item is not public. Requires authentication. ```typescript import { getItem } from "@esri/arcgis-rest-portal"; import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK••••"); getItem("6e03e8c26aad4b9c92a87c1063ddb0e3", { authentication: auth }) .then((item) => { console.log(item.title); // "World Time Zones" console.log(item.type); // "Feature Service" console.log(item.thumbnailUrl); // fully qualified authenticated URL console.log(item.tags); }); ``` -------------------------------- ### Find Places Near a Point Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-places/README.md Use the findPlacesNearPoint function to search for places. Ensure you provide valid coordinates, category IDs, and authentication details. ```javascript import { ApiKeyManager } from "@esri/arcgis-rest-request"; import { findPlacesNearPoint } from "@esri/arcgis-rest-places"; const { places } = await findPlacesNearPoint({ x: -3.1883, y: 55.9533, categoryIds: ["13002"], authentication: ApiKeyManager.fromKey("YOUR_API_KEY") }); console.log(places[0].name); ``` -------------------------------- ### Search Portal Items with `searchItems` Source: https://context7.com/esri/arcgis-rest-js/llms.txt Searches ArcGIS Online or Enterprise for items using a simple query string or a structured query builder. Requires authentication for private items. ```typescript import { searchItems, SearchQueryBuilder } from "@esri/arcgis-rest-portal"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; const session = await ArcGISIdentityManager.signIn({ username: "jane", password: "••••" }); // Simple string query searchItems("type:\"Feature Service\" AND access:public") .then((res) => console.log(`${res.total} public feature services found`)); // Structured query builder const query = new SearchQueryBuilder() .match("Esri") .in("owner") .and() .match("Web Map") .in("type"); searchItems({ q: query, num: 10, authentication: session }) .then((res) => res.results.forEach((item) => console.log(item.id, item.title))); ``` -------------------------------- ### Geocode an Address Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-geocoding/README.md Use the `geocode` function to convert an address string into geographic coordinates. The response contains an array of candidates, and the first candidate's location is typically the most relevant. ```javascript import { geocode } from "@esri/arcgis-rest-geocoding"; geocode("LAX").then((response) => { response.candidates[0].location; // => { x: -118.409, y: 33.943 } }); ``` -------------------------------- ### Solve a Route with @esri/arcgis-rest-routing Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-routing/README.md Use the solveRoute function to calculate a route between two or more stops. Ensure you have authentication configured for the request. ```javascript solveRoute({ stops: [ [-117.195677, 34.056383], [-117.918976, 33.812092] ], authentication }).then(response); // {routes: {features: [{attributes: { ... }, geometry:{ ... }}]}} ``` -------------------------------- ### serviceArea Source: https://context7.com/esri/arcgis-rest-js/llms.txt Calculates reachable areas (polygons) from one or more facility points given a set of break values (time, distance, etc.). ```APIDOC ## `serviceArea` — Drive-time / distance service areas Calculates reachable areas (polygons) from one or more facility points given a set of break values (time, distance, etc.). ```ts import { serviceArea } from "@esri/arcgis-rest-routing"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; const session = await ArcGISIdentityManager.signIn({ username: "jane", password: "••••" }); serviceArea({ facilities: [[-117.1956, 34.0572]], authentication: session, params: { defaultBreaks: [5, 10, 15], // minutes travelMode: "Driving Time" } }).then((res) => { const polygons = res.saPolygons!; console.log(polygons.features.length); // 3 (one per break value) console.log(polygons.geoJson?.features[0].geometry.type); // "Polygon" }); ``` ``` -------------------------------- ### ApiKeyManager — API key authentication Source: https://context7.com/esri/arcgis-rest-js/llms.txt Wraps a static ArcGIS API key (`AAPK…` prefix) into an `IAuthenticationManager`. Supports serialization to/from JSON for persistence across sessions (e.g. `localStorage`). ```APIDOC ## `ApiKeyManager` — API key authentication ### Description Wraps a static ArcGIS API key (`AAPK…` prefix) into an `IAuthenticationManager`. Supports serialization to/from JSON for persistence across sessions (e.g. `localStorage`). ### Method Static methods for creation and serialization/deserialization. ### Usage ```javascript import { ApiKeyManager } from "@esri/arcgis-rest-request"; // Create from a key string const auth = ApiKeyManager.fromKey("AAPK••••••••••••••••••••••••••••••"); // Persist to storage localStorage.setItem("auth", auth.serialize()); // Restore later const restored = ApiKeyManager.deserialize(localStorage.getItem("auth")!); // Pass to any request function import { geocode } from "@esri/arcgis-rest-geocoding"; geocode({ singleLine: "Eiffel Tower", authentication: restored }) .then((res) => console.log(res.candidates[0].location)); // => { x: 2.2945, y: 48.8584, spatialReference: { wkid: 4326 } } ``` ### Methods - **fromKey(key: string): ApiKeyManager** - Creates an `ApiKeyManager` instance from a given API key string. - **deserialize(json: string): ApiKeyManager** - Creates an `ApiKeyManager` instance from a JSON string. - **serialize(): string** - Serializes the `ApiKeyManager` instance to a JSON string. ### Parameters - **key** (string) - The ArcGIS API key. - **json** (string) - A JSON string representing a serialized `ApiKeyManager`. ### Response Returns an `ApiKeyManager` instance or a JSON string. ``` -------------------------------- ### Credential Message Object Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-request/post-message-auth-spec.md This JSON object is sent from the host application to the embedded application, containing the user's authentication credential. The embedded application is responsible for using this credential with functions like `exchangeToken` or `validateAppAccess`. ```json { "type": "arcgis:auth:credential", "credential": { "token": "thetoken", "userId": "jsmith", "server": "https://www.arcgis.com", "ssl": true, "expires": 1599831467093 } } ``` -------------------------------- ### ArcGISIdentityManager Source: https://context7.com/esri/arcgis-rest-js/llms.txt Handles OAuth 2.0 user authentication, including PKCE flow for browser applications and username/password for Node.js. It manages token refresh, federation, and serialization. ```APIDOC ## `ArcGISIdentityManager` — OAuth 2.0 user authentication Full OAuth 2.0 identity manager for user-facing applications. Supports PKCE (browser pop-up / redirect) and username+password sign-in. Handles token refresh, federation with ArcGIS Enterprise servers, and serialization. ### Browser: PKCE redirect flow #### Step 1 – redirect the user to the ArcGIS sign-in page ```ts import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; ArcGISIdentityManager.beginOAuth2({ clientId: "abc123", redirectUri: "https://myapp.com/auth-callback", pkce: true }); ``` #### Step 2 – after redirect, complete the flow ```ts const session = await ArcGISIdentityManager.completeOAuth2({ clientId: "abc123", redirectUri: "https://myapp.com/auth-callback" }); console.log(session.username); // "jane_doe" ``` ### Node.js: username + password ```ts const nodeSession = await ArcGISIdentityManager.signIn({ username: "jane_doe", password: "••••••••", portal: "https://www.arcgis.com/sharing/rest" }); // Serialize / deserialize for session persistence const json = nodeSession.serialize(); const rehydrated = ArcGISIdentityManager.deserialize(json); // fromToken – wrap an existing short-lived token const fromToken = ArcGISIdentityManager.fromToken({ token: "existing_token_string", tokenExpires: new Date(Date.now() + 60 * 60 * 1000), portal: "https://www.arcgis.com/sharing/rest" }); ``` ``` -------------------------------- ### ApplicationCredentialsManager — OAuth 2.0 client credentials (server-side) Source: https://context7.com/esri/arcgis-rest-js/llms.txt For server-side applications that authenticate as an application (not a user) using a Client ID and Client Secret. Automatically fetches and refreshes OAuth 2.0 tokens using the `client_credentials` grant. ```APIDOC ## `ApplicationCredentialsManager` — OAuth 2.0 client credentials (server-side) ### Description For server-side applications that authenticate as an application (not a user) using a Client ID and Client Secret. Automatically fetches and refreshes OAuth 2.0 tokens using the `client_credentials` grant. ### Method Static methods for creation. ### Usage ```javascript import { ApplicationCredentialsManager } from "@esri/arcgis-rest-request"; const session = ApplicationCredentialsManager.fromCredentials({ clientId: "abc123", clientSecret: "s3cr3t", // optional: point at an ArcGIS Enterprise portal portal: "https://myorg.maps.arcgis.com/sharing/rest", duration: 120 // token lifetime in minutes }); // Use with any request import { searchItems } from "@esri/arcgis-rest-portal"; searchItems({ q: "owner:esri", authentication: session }) .then((res) => res.results.forEach((item) => console.log(item.title))); ``` ### Methods - **fromCredentials(options: object): ApplicationCredentialsManager** - Creates an `ApplicationCredentialsManager` instance from client credentials. ### Parameters - **options** (object) - **clientId** (string) - Required - The application's client ID. - **clientSecret** (string) - Required - The application's client secret. - **portal** (string) - Optional - The URL of the ArcGIS Enterprise portal. - **duration** (number) - Optional - The token lifetime in minutes. ``` -------------------------------- ### findElevationAtManyPoints Source: https://context7.com/esri/arcgis-rest-js/llms.txt Returns surface elevations for an array of WGS 84 longitude/latitude coordinate pairs. Supports batch lookups and specifies elevation relative to mean sea level or ellipsoid. ```APIDOC ## `findElevationAtManyPoints` — Batch elevation lookup Returns surface elevations (in metres) for an array of WGS 84 longitude/latitude coordinate pairs. The coordinate bounding box must not exceed 50 km in either dimension. ### Parameters - `coordinates`: Array of [longitude, latitude] pairs. - `relativeTo`: Specifies the reference for elevation ('meanSeaLevel' or 'ellipsoid'). - `authentication`: Authentication object for accessing the service. ### Request Example ```javascript import { findElevationAtManyPoints } from "@esri/arcgis-rest-elevation"; import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK••••"); const results = await findElevationAtManyPoints({ // Each inner array: [longitude, latitude] coordinates: [ [31.1342, 29.9792], // Great Pyramid of Giza [31.1309, 29.9761], [31.1284, 29.9725] ], relativeTo: "meanSeaLevel", // or "ellipsoid" authentication: auth }); results.result.points.forEach((pt) => { console.log(`[${pt.coordinates}] → ${pt.elevation} m`); }); ``` ### Response - `result.points`: Array of objects, each containing coordinates and elevation. ``` -------------------------------- ### Generate Types from Open API Specification Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-elevation/README.md Generate TypeScript types from an Open API definition file using `openapi-typescript`. This is useful for ensuring type safety when interacting with ArcGIS REST services. ```bash npx openapi-typescript@5 URL_TO_RAW_SPEC_FILE --output packages/arcgis-rest-places/src/openapi-types.ts ``` -------------------------------- ### Error Message Object Source: https://github.com/esri/arcgis-rest-js/blob/main/packages/arcgis-rest-request/post-message-auth-spec.md This JSON object is sent from the host application to an embedded application when it declines to send credentials. The `error.message` property will contain the reason for the denial. ```json { "type": "arcgis:auth:error", "error": { "name": "", "message": "" } } ``` -------------------------------- ### Job Source: https://context7.com/esri/arcgis-rest-js/llms.txt Manages asynchronous ArcGIS geoprocessing jobs. Allows submitting jobs, monitoring their status, emitting events, and retrieving results. ```APIDOC ## `Job` — Long-running geoprocessing jobs Manages asynchronous ArcGIS geoprocessing jobs. Submits a job, polls for status updates at a configurable rate, emits events, and retrieves named result parameters. ### Submit a geoprocessing job ```ts import { Job, JOB_STATUSES } from "@esri/arcgis-rest-request"; import { ApiKeyManager } from "@esri/arcgis-rest-request"; const auth = ApiKeyManager.fromKey("AAPK••••"); const job = await Job.submitJob({ url: "https://analysis.arcgis.com/arcgis/rest/services/tasks/GPServer/CreateDriveTimeAreas", params: { inputLayer: { /* feature set */ }, breakValues: "5 10 15", breakUnits: "Minutes" }, authentication: auth, startMonitoring: false, pollingRate: 3000 }); console.log("Job ID:", job.id); // Listen for status events job.on("status", ({ jobStatus }) => { console.log("Status:", jobStatus); // e.g. "esriJobExecuting" }); // Wait for completion and fetch all results const results = await job.getAllResults(); console.log(results); // => { outputDriveTimeAreas: { paramUrl: "...", value: { features: [...] } } } // Or resume an existing job later const serialized = job.serialize(); const resumed = await Job.deserialize(serialized, { authentication: auth }); const driveTimeAreas = await resumed.getResult("outputDriveTimeAreas"); ``` ``` -------------------------------- ### createGroup Source: https://context7.com/esri/arcgis-rest-js/llms.txt Creates a new group in an ArcGIS Online or Enterprise organization. The authenticated user becomes the group owner. ```APIDOC ## `createGroup` — Create a portal group Creates a new group in an ArcGIS Online or Enterprise organization. The authenticated user becomes the group owner. ```ts import { createGroup } from "@esri/arcgis-rest-portal"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; const session = await ArcGISIdentityManager.signIn({ username: "jane", password: "••••" }); createGroup({ group: { title: "Field Survey Team", access: "org", // "private" | "org" | "public" description: "Internal group for field data collection workflows", tags: ["field", "survey", "mobile"], membershipAccess: "org" }, authentication: session }).then((res) => { console.log(res.success); // true console.log(res.group.id); // new group's ID }); ``` ```