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() async {2 let request = RESTRequest(path: "/todo")3 do {4 let data = try await Amplify.API.get(request: request)5 let str = String(decoding: data, as: UTF8.self)6 print("Success: \(str)")7 } catch let error as APIError {8 print("Failed due to API error: ", error)9 } catch {10 print("Unexpected error: \(error)")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.
1import AWSAPIPlugin
1if let error = error as? APIError,2 case let .httpStatusError(statusCode, response) = error,3 let awsResponse = response as? AWSHTTPURLResponse,4 let responseBody = awsResponse.body {5 print("Response contains a \(responseBody.count) byte long response body with status code: \(statusCode)")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() async {2 let queryParameters = ["q":"test"]3 let request = RESTRequest(path: "/todo", queryParameters: queryParameters)4 do {5 let data = try await Amplify.API.get(request: request)6 let str = String(decoding: data, as: UTF8.self)7 print("Success: \(str)")8 } catch let error as APIError {9 print("Failed due to API error: ", error)10 } catch {11 print("Unexpected error: \(error)")12 }13}