Fetch data
GET requests
To make a GET request, first create a RESTRequest object and then use the Amplify.API.get api to issue the request:
1func getTodo() {2 let request = RESTRequest(path: "/todo")3 Amplify.API.get(request: request) { result in4 switch result {5 case .success(let data):6 let str = String(decoding: data, as: UTF8.self)7 print("Success \(str)")8 case .failure(let apiError):9 print("Failed", apiError)10 }11 }12}
Handling non-2xx HTTP responses
When your service returns a non-2xx HTTP status code in the response, the API call will result in a failure that you can handle in your app. The response body can be accessed from the body: Data?
property. For example, when the APIError
is an .httpStatusError(StatusCode, HTTPURLResponse)
, then access the response body by type casting the response to an AWSHTTPURLResponse
and retrieve the body
field.
1if case let .httpStatusError(statusCode, response) = error,2 let awsResponse = response as? AWSHTTPURLResponse,3 let responseBody = awsResponse.body4{5 print("Response contains a \(responseBody.count) byte long response body")6}
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('/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:
1func getTodo() {2 let queryParameters = ["q":"test"]3 let request = RESTRequest(path: "/todo", queryParameters: queryParameters)4 Amplify.API.get(request: request) { result in5 switch result {6 case .success(let data):7 let str = String(decoding: data, as: UTF8.self)8 print("Success \(str)")9 case .failure(let apiError):10 print("Failed", apiError)11 }12 }13}