or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

analytics.mdapi.mdauth.mddatastore.mdindex.mdnotifications.mdserver.mdstorage.mdutilities.md
tile.json

api.mddocs/

API

REST and GraphQL API capabilities with support for AWS API Gateway, AWS AppSync, and custom endpoints. Provides both high-level client generation and low-level HTTP operations.

Capabilities

Core Import

import { get, post, put, del, patch, head, generateClient } from "aws-amplify/api";

Alternatively, you can use the data alias for API functionality:

// aws-amplify/data is an alias for aws-amplify/api
import { get, post, generateClient } from "aws-amplify/data";

REST API Operations

Perform HTTP operations against REST endpoints.

/**
 * Perform HTTP GET request
 * @param apiRequest - Request configuration
 * @returns Promise with response data
 */
function get(apiRequest: RestApiRequest): Promise<RestApiResponse>;

/**
 * Perform HTTP POST request
 * @param apiRequest - Request configuration
 * @returns Promise with response data
 */
function post(apiRequest: RestApiRequest): Promise<RestApiResponse>;

/**
 * Perform HTTP PUT request
 * @param apiRequest - Request configuration
 * @returns Promise with response data
 */
function put(apiRequest: RestApiRequest): Promise<RestApiResponse>;

/**
 * Perform HTTP DELETE request
 * @param apiRequest - Request configuration
 * @returns Promise with response data
 */
function del(apiRequest: RestApiRequest): Promise<RestApiResponse>;

/**
 * Perform HTTP PATCH request
 * @param apiRequest - Request configuration
 * @returns Promise with response data
 */
function patch(apiRequest: RestApiRequest): Promise<RestApiResponse>;

/**
 * Perform HTTP HEAD request
 * @param apiRequest - Request configuration
 * @returns Promise with response data
 */
function head(apiRequest: RestApiRequest): Promise<RestApiResponse>;

interface RestApiRequest {
  apiName: string;
  path: string;
  options?: {
    headers?: Record<string, string>;
    queryStringParameters?: Record<string, any>;
    body?: any;
  };
}

interface RestApiResponse {
  statusCode: number;
  headers: Record<string, string>;
  body: any;
}

Usage Example:

import { get, post } from "aws-amplify/api";

// GET request
const response = await get({
  apiName: "myRestApi",
  path: "/users",
  options: {
    headers: {
      "Content-Type": "application/json"
    },
    queryStringParameters: {
      limit: 10,
      offset: 0
    }
  }
});

// POST request
const createResponse = await post({
  apiName: "myRestApi", 
  path: "/users",
  options: {
    body: {
      name: "John Doe",
      email: "john@example.com"
    }
  }
});

Request Cancellation

Check if an error is due to request cancellation.

/**
 * Check if an error is a cancellation error
 * @param error - Error to check
 * @returns Boolean indicating if error is from cancellation
 */
function isCancelError(error: any): boolean;

GraphQL Client

Generate strongly-typed GraphQL clients for AWS AppSync.

/**
 * Generate a GraphQL client with optional type safety
 * @returns GraphQL client instance
 */
function generateClient<T = never>(): Client<T>;

interface Client<T> {
  /**
   * Execute GraphQL operations (queries, mutations, subscriptions)
   * @param query - GraphQL query with variables
   * @returns Promise with query result
   */
  graphql<K extends keyof T>(query: GraphQLQuery<T, K>): Promise<GraphQLResult<T[K]>>;
  
  /**
   * Cancel all pending requests for this client
   */
  cancel(): void;
  
  /**
   * Check if client has been cancelled
   */
  readonly isCancelled: boolean;
}

interface GraphQLQuery<T, K extends keyof T> {
  query: string;
  variables?: any;
  authMode?: AuthMode;
  authToken?: string;
}

interface GraphQLResult<T> {
  data: T;
  errors?: GraphQLError[];
  extensions?: Record<string, any>;
}

interface GraphQLError {
  message: string;
  locations?: Array<{
    line: number;
    column: number;
  }>;
  path?: Array<string | number>;
  extensions?: Record<string, any>;
}

type AuthMode = 
  | 'apiKey'
  | 'userPool'
  | 'oidc' 
  | 'userCredentials'
  | 'none';

Usage Examples:

import { generateClient } from "aws-amplify/api";

// Generate untyped client
const client = generateClient();

// Execute query
const result = await client.graphql({
  query: `
    query GetTodos {
      listTodos {
        items {
          id
          name
          description
          completed
        }
      }
    }
  `
});

// Execute mutation with variables
const createResult = await client.graphql({
  query: `
    mutation CreateTodo($input: CreateTodoInput!) {
      createTodo(input: $input) {
        id
        name
        description
        completed
      }
    }
  `,
  variables: {
    input: {
      name: "Buy groceries",
      description: "Milk, bread, eggs",
      completed: false
    }
  }
});

// Execute with specific auth mode
const privateResult = await client.graphql({
  query: `
    query GetPrivateTodos {
      listPrivateTodos {
        items {
          id
          name
        }
      }
    }
  `,
  authMode: 'userPool'
});

Typed GraphQL Client

For TypeScript projects with generated types:

// Assuming you have generated types
interface Schema {
  listTodos: {
    items: Todo[];
    nextToken?: string;
  };
  getTodo: Todo;
  createTodo: Todo;
}

interface Todo {
  id: string;
  name: string;
  description?: string;
  completed: boolean;
  createdAt: string;
  updatedAt: string;
}

// Generate typed client
const typedClient = generateClient<Schema>();

// Now you get full type safety
const { data } = await typedClient.graphql({
  query: `query ListTodos { listTodos { items { id name } } }`
});
// data.listTodos.items is properly typed as Todo[]

GraphQL Subscriptions

Subscribe to real-time GraphQL updates.

// Subscriptions return observables for real-time updates
interface Subscription<T> {
  subscribe(observer: {
    next?: (value: T) => void;
    error?: (error: any) => void;
    complete?: () => void;
  }): { unsubscribe(): void };
}

Usage Example:

const subscription = client.graphql({
  query: `
    subscription OnCreateTodo {
      onCreateTodo {
        id
        name
        description
        completed
      }
    }
  `
}).subscribe({
  next: ({ data }) => {
    console.log('New todo created:', data.onCreateTodo);
  },
  error: (err) => {
    console.error('Subscription error:', err);
  }
});

// Unsubscribe when done
subscription.unsubscribe();

GraphQL Events and Connection State

Monitor GraphQL connection state and events.

/**
 * Events channel for GraphQL connection monitoring
 */
const events: EventsChannel;

/**
 * Connection state change event constant
 */
const CONNECTION_STATE_CHANGE: string;

interface EventsChannel {
  /**
   * Subscribe to connection state changes
   * @param eventName - Event to listen for
   * @param callback - Function to call on event
   * @returns Unsubscribe function
   */
  subscribe(eventName: string, callback: (data: any) => void): () => void;
}

enum ConnectionState {
  Connected = 'Connected',
  ConnectedPendingDisconnect = 'ConnectedPendingDisconnect', 
  ConnectedPendingKeepAlive = 'ConnectedPendingKeepAlive',
  ConnectedPendingNetwork = 'ConnectedPendingNetwork',
  Connecting = 'Connecting',
  ConnectionDisrupted = 'ConnectionDisrupted',
  ConnectionDisruptedPendingNetwork = 'ConnectionDisruptedPendingNetwork',
  Disconnected = 'Disconnected'
}

Usage Example:

import { events, CONNECTION_STATE_CHANGE } from "aws-amplify/api";

const unsubscribe = events.subscribe(CONNECTION_STATE_CHANGE, (data) => {
  console.log('Connection state changed:', data.connectionState);
  
  switch (data.connectionState) {
    case 'Connected':
      console.log('GraphQL connected');
      break;
    case 'Disconnected':
      console.log('GraphQL disconnected');
      break;
    case 'Connecting':
      console.log('GraphQL connecting...');
      break;
  }
});

// Unsubscribe when component unmounts
unsubscribe();

Advanced GraphQL Options

Configure GraphQL client behavior and options.

interface EventsOptions {
  /**
   * Maximum retry attempts for failed connections
   */
  maxRetryAttempts?: number;
  
  /**
   * Retry delay in milliseconds
   */
  retryDelayMs?: number;
  
  /**
   * Connection timeout in milliseconds
   */
  connectionTimeoutMs?: number;
}

Custom Headers and Authorization

Add custom headers and authorization to requests.

// Custom headers for REST API
const response = await get({
  apiName: "myApi",
  path: "/protected",
  options: {
    headers: {
      "Authorization": "Bearer " + customToken,
      "Custom-Header": "value"
    }
  }
});

// Custom authorization for GraphQL
const result = await client.graphql({
  query: `query GetData { getData { id } }`,
  authMode: 'oidc',
  authToken: customOIDCToken
});

Types

// Selection set for GraphQL type safety
type SelectionSet = string;

// GraphQL operation return type helper
type GraphQLReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

// GraphQL subscription type
interface GraphQLSubscription<T = any> {
  query: string;
  variables?: Record<string, any>;
  authMode?: AuthMode;
  authToken?: string;
}

// Error types
class GraphQLAuthError extends Error {
  name: 'GraphQLAuthError';
  message: string;
  graphQLErrors?: GraphQLError[];
  networkError?: Error;
}

class ApiError extends Error {
  name: 'ApiError';
  message: string;
  statusCode?: number;
  headers?: Record<string, string>;
  body?: any;
}

Error Handling

API operations can throw various errors:

import { ApiError, GraphQLAuthError, isCancelError } from "aws-amplify/api";

try {
  const response = await get({ apiName: "myApi", path: "/data" });
} catch (error) {
  if (isCancelError(error)) {
    console.log('Request was cancelled');
  } else if (error instanceof ApiError) {
    console.log(`API Error: ${error.statusCode} - ${error.message}`);
  } else {
    console.log('Unexpected error:', error);
  }
}

// GraphQL error handling
try {
  const result = await client.graphql({ query: myQuery });
} catch (error) {
  if (error instanceof GraphQLAuthError) {
    console.log('GraphQL auth error:', error.message);
    console.log('GraphQL errors:', error.graphQLErrors);
  } else {
    console.log('GraphQL error:', error);
  }
}