Connect your app code to API
In this guide, you will connect your application code to the backend API using the Amplify Libraries. Before you begin, you will need:
- Your cloud sandbox with an Amplify Data resource up and running (
npx ampx sandbox
) - A frontend application set up with the Amplify library installed
- npm installed
Configure the Amplify Library
When you deploy you're iterating on your backend (npx ampx sandbox
), an amplify_outputs.json file is generated for you. This file contains your API's endpoint information and auth configurations. Add the following code to your app's entrypoint to initialize and configure the Amplify client library:
Configure authorization mode
The Authorization Mode determines how a request should be authorized with the backend. By default, Amplify Data uses the "userPool" authorization which uses the signed-in user credentials to sign an API request. If you use a allow.publicApiKey()
authorization rules for your data models, you need to use "apiKey" as an authorization mode. Review Customize your auth rules to learn more about which authorization modes to choose for which type of request. A Default Authorization Mode is provided as part of the amplify_outputs.json that is generated upon a successful deployment.
Set authorization mode on the request-level
You can also specify the authorization mode on each individual API request. This is useful if your application typically only uses one authorization mode with a small number of exceptions.
let result = try await Amplify.API.query( request: .list( Todo.self, authMode: .apiKey))
let result = try await Amplify.API.query( request: .list( Todo.self, authMode: .amazonCognitoUserPools))
let result = try await Amplify.API.query( request: .list( Todo.self, authMode: .awsIAM))
let result = try await Amplify.API.query( request: .list( Todo.self, authMode: .openIDConnect))
Set custom request headers
When working with the Amplify Data endpoint, you may need to set request headers for authorization purposes or to pass additional metadata from your frontend to the backend API.
To include custom headers in your outgoing requests, add an URLRequestInterceptor
to the AWSAPIPlugin
.
import Amplifyimport AWSAPIPlugin
struct CustomInterceptor: URLRequestInterceptor { func intercept(_ request: URLRequest) throws -> URLRequest { var request = request request.setValue("headerValue", forHTTPHeaderField: "headerKey") return request }}let apiPlugin = AWSAPIPlugin(modelRegistration: AmplifyModels())try apiPlugin.add(interceptor: CustomInterceptor(), for: AWSAPIPlugin.defaultGraphQLAPI)try Amplify.add(plugin: apiPlugin)try Amplify.configure(with: .amplifyOutputs)