Grant Lambda function access to API and Data
Function access to defineData
can be configured using an authorization rule on the schema object.
import { a, defineData, defineFunction, type ClientSchema} from '@aws-amplify/backend';
const functionWithDataAccess = defineFunction({ entry: '../functions/data-access.ts'});
const schema = a .schema({ Todo: a.model({ name: a.string(), description: a.string() }) }) .authorization(allow => [allow.resource(functionWithDataAccess)]);
export type Schema = ClientSchema<typeof schema>;
export const data = defineData({ schema});
The object returned from defineFunction
can be passed directly to allow.resource()
in the schema authorization rules. This will grant the function the ability to execute Query, Mutation, and Subscription operations against the GraphQL API. Use the .to()
method to narrow down access to one or more operations.
const schema = a .schema({ Todo: a.model({ name: a.string(), description: a.string() }) }) .authorization(allow => [ allow.resource(functionWithDataAccess).to(['query', 'listen']) ]); // allow query and subscription operations but not mutations
When configuring function access, the function will be provided the API endpoint as an environment variable named <defineDataName>_GRAPHQL_ENDPOINT
, where defineDataName
is transformed to SCREAMING_SNAKE_CASE. The default name is AMPLIFY_DATA_GRAPHQL_ENDPOINT
unless you have specified a different name in defineData
.
Access the API using aws-amplify
In the handler file for your function, configure the Amplify data client
import { Amplify } from 'aws-amplify';import { generateClient } from 'aws-amplify/data';import { Schema } from '../data/resource';import { env } from '$amplify/env/<function-name>'; // replace with your function name
Amplify.configure( { API: { GraphQL: { endpoint: env.<amplifyData>_GRAPHQL_ENDPOINT, // replace with your defineData name region: env.AWS_REGION, defaultAuthMode: 'identityPool' } } }, { Auth: { credentialsProvider: { getCredentialsAndIdentityId: async () => ({ credentials: { accessKeyId: env.AWS_ACCESS_KEY_ID, secretAccessKey: env.AWS_SECRET_ACCESS_KEY, sessionToken: env.AWS_SESSION_TOKEN, }, }), clearCredentialsAndIdentityId: () => { /* noop */ }, }, }, });
const dataClient = generateClient<Schema>();
export const handler = async (event) => { // your function code goes here}
Use the command below to generate GraphQL client code to call your data backend.
npx ampx generate graphql-client-code --out <path-function-handler-dir>/graphql
Once you have generated the client code, update the function to access the data. The following code creates a todo and then lists all todos.
const client = generateClient<Schema>();
export const handler = async (event) => { await client.graphql({ query: createTodo, variables: { input: { name: "My first todo", description: "This is my first todo", }, }, });
await client.graphql({ query: listTodos, });
return event;};