Fetch data
To invoke an endpoint, you need to set input object with required apiName
option and optional headers
, queryParams
, and body
options. API status
code response > 299 are thrown as an RestApiError
instance. The error instance
provides name
and message
properties parsed from the response.
GET requests
1import { get } from 'aws-amplify/api';2
3async function getTodo() {4 try {5 const restOperation = get({ 6 apiName: 'todo-api',7 path: '/todo' 8 });9 const response = await restOperation.response;10 console.log('GET call succeeded: ', response);11 } catch (error) {12 console.log('GET call failed: ', error);13 }14}
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};
Alternatively, you can update your backend file which is located at amplify/backend/function/[your-lambda-function]/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('/items', 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:
1async function getTodo() {2 try {3 const restOperation = get({4 apiName: 'todo-api',5 path: '/todo',6 options: {7 queryParams: {8 id: '123'9 }10 }11 });12 const response = await restOperation.response;13 console.log('GET call succeeded: ', response);14 } catch (error) {15 console.log('GET call failed: ', error);16 }17}
Accessing response payload
You can consume the response payload by accessing the body
property of the response object.
Depending on the use case and the content type of the body, you can consume they payload in string, blob or JSON.
1// ...2const { body } = await restOperation.response;3// consume as a string:4const str = await body.text();5// OR consume as a blob:6const blob = await body.blob();7// OR consume as a JSON:8const json = await body.json();