Skip to content

Commit 63f71b5

Browse files
committed
feature(function): add custom functions documentation for AWS Amplify Gen 2 @aws-amplify/amplify-backend/1602
1 parent a001291 commit 63f71b5

File tree

3 files changed

+237
-3
lines changed

3 files changed

+237
-3
lines changed

cspell.json

+14-3
Original file line numberDiff line numberDiff line change
@@ -1618,14 +1618,25 @@
16181618
"knowledgebases",
16191619
"rehype",
16201620
"assetlinks",
1621-
"AMPLIFYRULES"
1621+
"AMPLIFYRULES",
1622+
"manylinux",
1623+
"GOARCH",
1624+
"norpc"
1625+
],
1626+
"flagWords": [
1627+
"hte",
1628+
"full-stack",
1629+
"Full-stack",
1630+
"Full-Stack",
1631+
"sudo"
16221632
],
1623-
"flagWords": ["hte", "full-stack", "Full-stack", "Full-Stack", "sudo"],
16241633
"patterns": [
16251634
{
16261635
"name": "youtube-embed-ids",
16271636
"pattern": "/embedId=\".*\" /"
16281637
}
16291638
],
1630-
"ignoreRegExpList": ["youtube-embed-ids"]
1639+
"ignoreRegExpList": [
1640+
"youtube-embed-ids"
1641+
]
16311642
}

src/directory/directory.mjs

+3
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,9 @@ export const directory = {
448448
},
449449
{
450450
path: 'src/pages/[platform]/build-a-backend/functions/modify-resources-with-cdk/index.mdx'
451+
},
452+
{
453+
path: 'src/pages/[platform]/build-a-backend/functions/custom-functions/index.mdx'
451454
}
452455
]
453456
},
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
import { getCustomStaticPath } from '@/utils/getCustomStaticPath';
2+
3+
export const meta = {
4+
title: 'Custom functions',
5+
description:
6+
'Use another AWS Lambda runtimes like python, golang to perform tasks and customize workflows.',
7+
platforms: [
8+
'android',
9+
'angular',
10+
'flutter',
11+
'javascript',
12+
'nextjs',
13+
'react',
14+
'react-native',
15+
'swift',
16+
'vue'
17+
]
18+
};
19+
20+
export function getStaticPaths() {
21+
return getCustomStaticPath(meta.platforms);
22+
}
23+
24+
export function getStaticProps(context) {
25+
return {
26+
props: {
27+
platform: context.params.platform,
28+
meta
29+
}
30+
};
31+
}
32+
33+
AWS Amplify Gen 2 Functions are AWS Lambda functions that can be used to perform tasks and customize workflows in your Amplify app.Functions can be written in Node.js, Python, Go, or any other language supported by AWS Lambda:
34+
35+
<Callout warning>
36+
37+
**Note:** Custom runtimes are not supported in Amplify Functions directly. If you need docker support to use a custom runtime for example in Python, Docker is not supported in Amplify Hosting and Amplify backend auto build. You shouldn't use docker build in your function.There is an example of how to use python in a lambda function in the without Docker section below.
38+
39+
</Callout>
40+
41+
Technically, you can use any language supported by AWS Lambda. These are NodeJS, Python, Java, .NET, Ruby.
42+
To use other languages in Lambda, such as Go or Rust, use an OS-only runtime.
43+
44+
In this guide, you will learn how to create python and golang functions in Amplify Functions.
45+
46+
# Python functions
47+
To get started, create a new directory and a resource file, `amplify/functions/say-hello/resource.ts`. Then, define the Function with `defineFunction`:
48+
49+
```ts title="amplify/functions/say-hello/resource.ts"
50+
import { defineFunction } from "@aws-amplify/backend";
51+
import { DockerImage, Duration } from "aws-cdk-lib";
52+
import { Code, Function, Runtime } from "aws-cdk-lib/aws-lambda";
53+
import { execSync } from "child_process";
54+
import * as path from "path";
55+
56+
export const sayHello = defineFunction(
57+
(scope) =>
58+
new Function(scope, "say-hello", {
59+
handler: "index.handler",
60+
runtime: Runtime.PYTHON_3_9, // or any other python version
61+
timeout: Duration.seconds(20), // default is 3 seconds
62+
code: Code.fromAsset(functionDir, {
63+
bundling: {
64+
image: DockerImage.fromRegistry("dummy"),
65+
local: {
66+
tryBundle(outputDir: string) {
67+
execSync(
68+
`python3 -m pip install -r ${path.join(functionDir, "requirements.txt")} -t ${path.join(outputDir)} --platform manylinux2014_x86_64 --only-binary=:all:`
69+
);
70+
execSync(`rsync -rLv ${functionDir}/* ${path.join(outputDir)}`);
71+
return true;
72+
},
73+
},
74+
},
75+
}),
76+
})
77+
);
78+
```
79+
80+
Next, create the corresponding handler file at `amplify/functions/say-hello/handler.ts`. This is where your function code will go.
81+
82+
```ts title="amplify/functions/say-hello/index.py"
83+
import json
84+
85+
def handler(event, context):
86+
return {
87+
"statusCode": 200,
88+
"body": json.dumps({
89+
"message": "Hello World",
90+
}),
91+
}
92+
```
93+
94+
The handler file _must_ export a function named "handler". This is the entry point to your function. For more information on writing functions, refer to the [AWS documentation for Lambda function handlers using python](https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html).
95+
96+
If you need python packages, you can add them to a `requirements.txt` file in the same directory as your handler file. The `bundling` option in the `Code.fromAsset` method will install these packages for you.
97+
Create a `requirements.txt` file in the same directory as your handler file. This file should contain the names of the packages you want to install. For example:
98+
99+
```txt title="amplify/functions/say-hello/requirements.txt"
100+
request==2.25.1
101+
some-other-package>=1.0.0
102+
```
103+
104+
You're now ready to deploy your python function. Next is the same process as the Node.js/TypeScript function. Go to [Common steps for all languages](#common-steps-for-all-languages) to continue.
105+
106+
# Go functions
107+
To get started, install go package from npm. go to your backend directory, you should see amplify folder inside it. and run the following command:
108+
```npm i @aws-cdk/aws-lambda-go-alpha```
109+
110+
create a new directory and a resource file, `amplify/functions/say-hello/resource.ts`. Then, define the Function with `defineFunction`:
111+
112+
```ts title="amplify/functions/say-hello/resource.ts"
113+
import { defineFunction } from "@aws-amplify/backend";
114+
import { GoFunction } from "@aws-cdk/aws-lambda-go-alpha";
115+
import { Runtime } from "aws-cdk-lib/aws-lambda";
116+
117+
export const sendSmsGoFunctionHandler = defineFunction((scope) => {
118+
return new GoFunction(scope, "say-hello", {
119+
entry: "./amplify/function/say-hello/",
120+
runtime: Runtime.PROVIDED_AL2023,
121+
environment: {
122+
GOARCH: "amd64",
123+
},
124+
bundling: {
125+
goBuildFlags: ["-tags lambda.norpc"],
126+
},
127+
});
128+
});
129+
```
130+
131+
Next, create the corresponding handler file at `amplify/functions/say-hello/main.go`. This is where your function code will go.
132+
133+
```go title="amplify/functions/say-hello/main.go"
134+
package main
135+
136+
import (
137+
"context"
138+
"fmt"
139+
140+
"github.com/aws/aws-lambda-go/lambda"
141+
)
142+
143+
type Event struct {
144+
Arguments Arguments `json:"arguments"`
145+
}
146+
147+
type Arguments struct {
148+
Title string `json:"phone"`
149+
Msg string `json:"msg"`
150+
}
151+
152+
func HandleRequest(ctx context.Context, event Event) (string, error) {
153+
fmt.Println("Received event: ", event)
154+
155+
// fmt.Println("Message sent to: ", event.Arguments.Msg)
156+
// You can use lambda arguments in your code
157+
158+
return "Hello World!", nil
159+
}
160+
161+
func main() {
162+
lambda.Start(HandleRequest)
163+
}
164+
```
165+
166+
Then you should run the following command to build the go function:
167+
```bash title="terminal"
168+
go mod init lambda
169+
```
170+
then run to install the dependencies.
171+
172+
```bash title="terminal"
173+
go mod tidy
174+
```
175+
176+
You're now ready to deploy your golang function. Next is the same process as the Node.js/TypeScript function.
177+
178+
# Common steps for all languages
179+
Lastly, this function needs to be added to your backend.
180+
181+
```ts title="amplify/backend.ts"
182+
import { defineBackend } from '@aws-amplify/backend';
183+
// highlight-next-line
184+
import { sayHello } from './functions/say-hello/resource';
185+
186+
defineBackend({
187+
// highlight-next-line
188+
sayHello
189+
});
190+
```
191+
192+
Now when you run `npx ampx sandbox` or deploy your app on Amplify, it will include your Function.
193+
194+
To invoke your Function, we recommend adding your [Function as a handler for a custom query with your Amplify Data resource](/[platform]/build-a-backend/data/custom-business-logic/). This will enable you to strongly type Function arguments and the return statement, and use this to author your Function's business logic. To get started, open your `amplify/data/resource.ts` file and specify a new query in your schema:
195+
196+
```ts title="amplify/data/resource.ts"
197+
import { type ClientSchema, a, defineData } from "@aws-amplify/backend"
198+
import { sayHello } from "../functions/say-hello/resource"
199+
200+
const schema = a.schema({
201+
// highlight-start
202+
sayHello: a
203+
.query()
204+
.arguments({
205+
name: a.string(),
206+
})
207+
.returns(a.string())
208+
.handler(a.handler.function(sayHello)),
209+
// highlight-end
210+
})
211+
212+
export type Schema = ClientSchema<typeof schema>
213+
214+
export const data = defineData({
215+
schema,
216+
authorizationModes: {
217+
defaultAuthorizationMode: "iam",
218+
},
219+
})
220+
```

0 commit comments

Comments
 (0)