The Google Cloud client libraries for Swift automatically configure the authentication credentials used to authenticate requests to Google Cloud. Some applications might need to override the default credentials. This document shows you how to override the default authentication credentials.
Before you begin
This document uses the Cloud Natural Language API. To enable this API, follow the Natural Language API setup guide.
Add the swift-google-cloud-language-v2 and swift-google-auth packages to
your Package.swift dependencies, and create an API key to
pass to your application.
For complete setup instructions for the Swift client libraries, see Quickstart: Get started with Swift.
Override the default credentials with an API key
API keys are text strings that grant access to some Google Cloud services. API keys require less configuration than other authentication methods. Before you use API keys, read Best practices for managing API keys to understand the associated security risks.
In this example, you configure the Natural Language API client to authenticate using an API key:
Add the imports required to use the client library and authentication types:
Write a function that receives the API key as a parameter:
Create a
Credentialsinstance with the API key, and pass it toClientOptionswhen initializing the client:Use the client to analyze the sentiment of a text document:
Calling analyzeSentiment succeeds with the configured API key and returns an
AnalyzeSentimentResponse containing the document's sentiment score and
magnitude.
Complete code
The following example shows the complete code for this document:
What's next
- Learn how to override the default endpoint.
- Learn how to enable debug logging to troubleshoot requests and responses.
- Learn how to configure package traits for large client libraries.
- Browse the Google Cloud client libraries for Swift reference documentation.