Fetch data
GET requests
To make a GET request use Amplify.API.get
:
1Future<void> getTodo() async {2 try {3 const options = RestOptions(path: '/todo');4 final restOperation = Amplify.API.get(restOptions: options);5 final response = await restOperation.response;6 print('GET call succeeded: ${response.body}');7 } on ApiException catch (e) {8 print('GET call failed: $e');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:
1exports.handler = function(event, context, callback) {2 console.log(event.queryStringParameters);3 console.log('body: ', event.body);4}
In case you do not have it already, alternatively, you can update your backend file which is located at amplify/backend/function/[your-lambda-function]/src/app.js
with the middleware:
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
:
1app.get('/todo', function(req, res) {2 const query = req.query;3 // or4 // const query = req.apiGateway.event.queryStringParameters5 res.json({6 event: req.apiGateway.event, // to view all event data7 query: query8 });9});
Then you can use query parameters in your path as follows:
1Future<void> getTodo() async {2 try {3 const options = RestOptions(4 path: '/todo',5 queryParameters: {'q' : 'test'},6 );7 final restOperation = Amplify.API.get(restOptions: options);8 final response = await restOperation.response;9 print('GET call succeeded');10 print(response.body);11 } on ApiException catch (e) {12 print('GET call failed: $e');13 }14}