Page updated Nov 14, 2023

Fetch data

GET requests

To make a GET request, first build a RestOptions object and then use the Amplify.API.get api to issue the request:

void getTodo() { RestOptions options = RestOptions.builder() .addPath("/todo") .build(); Amplify.API.get(options, restResponse -> Log.i("MyAmplifyApp", "GET succeeded: " + restResponse), apiFailure -> Log.e("MyAmplifyApp", "GET failed.", apiFailure) ); }
1void getTodo() {
2 RestOptions options = RestOptions.builder()
3 .addPath("/todo")
4 .build();
5
6 Amplify.API.get(options,
7 restResponse -> Log.i("MyAmplifyApp", "GET succeeded: " + restResponse),
8 apiFailure -> Log.e("MyAmplifyApp", "GET failed.", apiFailure)
9 );
10}

Accessing query parameters & body in Lambda proxy function

To learn more about Lambda Proxy Integration, please visit Amazon API Gateway Developer Guide.

If you are using a REST API which is generated with Amplify CLI, your backend is created with Lambda Proxy Integration, and you can access your query parameters & body within your Lambda function via the event object:

exports.handler = function(event, context, callback) { console.log(event.queryStringParameters); console.log('body: ', event.body); }
1exports.handler = function(event, context, callback) {
2 console.log(event.queryStringParameters);
3 console.log('body: ', event.body);
4}

Alternatively, you can update your backend file which is located at amplify/backend/function/[your-lambda-function]/app.js with the middleware:

const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware'); app.use(awsServerlessExpressMiddleware.eventContext());
1const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');
2app.use(awsServerlessExpressMiddleware.eventContext());

Accessing Query Parameters with Serverless Express

In your request handler use req.apiGateway.event or req.query:

app.get('/todo', function(req, res) { const query = req.query; // or // const query = req.apiGateway.event.queryStringParameters res.json({ event: req.apiGateway.event, // to view all event data query: query }); });
1app.get('/todo', function(req, res) {
2 const query = req.query;
3 // or
4 // const query = req.apiGateway.event.queryStringParameters
5 res.json({
6 event: req.apiGateway.event, // to view all event data
7 query: query
8 });
9});

Then you can use query parameters in your path as follows:

RestOptions options = RestOptions.builder() .addPath("/todo") .addQueryParameters(Collections.singletonMap("q", "test")) .build(); Amplify.API.get(options, response -> Log.i("MyAmplifyApp", "GET succeeded: " + response), error -> Log.e("MyAmplifyApp", "GET failed.", error) );
1RestOptions options = RestOptions.builder()
2 .addPath("/todo")
3 .addQueryParameters(Collections.singletonMap("q", "test"))
4 .build();
5
6Amplify.API.get(options,
7 response -> Log.i("MyAmplifyApp", "GET succeeded: " + response),
8 error -> Log.e("MyAmplifyApp", "GET failed.", error)
9);