Google service account authentication for the Google APIs.
import google
Server programs reach the Google APIs through a "service account". Get the account JSON file from the Google console, read it with ParseServiceAccount, and get a token for the scope you need with AccessToken; then send it in your net.http requests with Authorization. Keep the service account file as carefully as a password.
The package does one job: it signs a JWT with the account's RSA key (RS256), trades it at Google's token endpoint for an OAuth access token, and keeps that token for reuse. The calls to the APIs themselves are ordinary HTTP requests that you write. For Web Push to browsers without Firebase, see webpush.
Things that catch people out:
- Only service account keys are supported. A user's own Google login (the OAuth consent screen) and the metadata server that Google Cloud machines offer are not.
- When
AccessTokenfails,okis false and there is no message. Check in this order: the account'sok, the clock of the machine (a clock that is minutes off makes Google reject the signature), the network, and whether the API is enabled for the project. - A token is kept for 59 minutes per account and scope, shared by all threads. After you change the account's roles, call
Forgetso the next call fetches a fresh one.
Loading the service account safely
Download the JSON key from the Google Cloud console (IAM, Service accounts, Keys) and keep it outside the source tree; the usual place to point at it is the GOOGLE_APPLICATION_CREDENTIALS environment variable, read with env.GetOr. ParseServiceAccount never fails loudly: it returns an account whose ok is false when the text is empty or client_email or private_key is missing. Check it once at start up and stop with a clear message, so a bad deployment fails at once instead of at the first push notification.
import google
import io
func load(path: str): google.ServiceAccount:
text := io.ReadFile(path)
if text == "":
println "cannot read", path
ret google.ServiceAccount {}
end
account := google.ParseServiceAccount(text)
if not account.ok:
println path, "is not a service account file: client_email or private_key is missing"
end
ret account
end
func main:
io.WriteFile("good.json", `{"type":"service_account","project_id":"shop-prod","client_email":"push@shop-prod.iam.gserviceaccount.com","private_key":"-----BEGIN PRIVATE KEY-----\nMIIE...\n-----END PRIVATE KEY-----\n"}`)
io.WriteFile("broken.json", `{"type":"service_account","project_id":"shop-prod"}`)
each p in ["good.json", "broken.json", "missing.json"]:
account := load(p)
if account.ok:
println "project", account.project_id, "as", account.client_email
println "key loaded:", account.private_key.Len() > 0
end
end
endThe program prints the project and the account email, which are safe to log, but only whether the key was loaded. Never print or log private_key, and never commit the file: anyone who has it can act as your service.
Sending a push notification with Firebase
Firebase Cloud Messaging takes one HTTP request per message. Get a token for SCOPE_FCM, put it in the Authorization header, and post the message to /v1/projects/PROJECT/messages:send. AccessToken keeps the token and reuses it until shortly before it expires, so calling it before every message costs nothing after the first time.
import google
import io
import net.http
func send_push(account: google.ServiceAccount, device_token: str, title: str, body: str): bool:
mut ok := false
token := google.AccessToken(account, google.SCOPE_FCM, ok)
if not ok:
println "no access token"
ret false
end
url := "https://fcm.googleapis.com/v1/projects/" + account.project_id + "/messages:send"
message := ```
{"message": {"token": "${{ device_token }}", "notification": {"title": "${{ title }}", "body": "${{ body }}"}}}
```
mut headers := http.NewHeaders()
headers.Insert("Authorization", google.Authorization(token))
headers.Insert("Content-Type", "application/json")
r := http.PostWith(url, message, headers)
if http.Status(r) != 200:
println "FCM answered", http.Status(r), http.Body(r)
ret false
end
println "sent:", http.Body(r)
ret true
end
func main:
account := google.ParseServiceAccount(io.ReadFile("service-account.json"))
if not account.ok:
println "service-account.json is missing or invalid"
ret 1
end
send_push(account, "DEVICE_REGISTRATION_TOKEN", "Order shipped", "Your parcel is on its way")
send_push(account, "DEVICE_REGISTRATION_TOKEN", "Delivered", "Your parcel has arrived")
ret 0
endThis needs a real service account with the Firebase Cloud Messaging API enabled and a device registration token from your app, so it is only compiled here. Save the key as service-account.json and replace DEVICE_REGISTRATION_TOKEN. On success the body holds the message name, {"name": "projects/.../messages/..."}; an error whose body says UNREGISTERED means the app was removed from the device and you should delete that token. The title and body are put into the JSON as they are; if they can contain quotes, build the message with encoding.json instead.
Uploading a file to Cloud Storage
A simple upload is one POST of the file's bytes to the upload endpoint, with the object name in the query string and the content type in a header. The token comes from SCOPE_STORAGE. Object names may contain /, so encode the name with encoding.url before it goes into the URL.
import google
import io
import net.http
import encoding.url
func upload(account: google.ServiceAccount, bucket: str, name: str, content: str, kind: str): bool:
mut ok := false
token := google.AccessToken(account, google.SCOPE_STORAGE, ok)
if not ok:
ret false
end
target := "https://storage.googleapis.com/upload/storage/v1/b/" + bucket + "/o?uploadType=media&name=" + url.EncodePathSegment(name)
mut headers := http.NewHeaders()
headers.Insert("Authorization", google.Authorization(token))
headers.Insert("Content-Type", kind)
r := http.PostWith(target, content, headers)
println name, "->", http.Status(r)
ret http.Status(r) == 200
end
func main:
account := google.ParseServiceAccount(io.ReadFile("service-account.json"))
if not account.ok:
println "service-account.json is missing or invalid"
ret 1
end
upload(account, "my-bucket", "reports/2026-10.csv", "day,sales\n1,120\n2,95\n", "text/csv")
upload(account, "my-bucket", "notes/hello.txt", "salam", "text/plain")
google.Forget(account)
ret 0
endReplace my-bucket with a bucket the service account can write to (the Storage Object Creator role is enough). A status of 200 means the object was stored; 403 means the account lacks permission on that bucket. Forget drops the kept token, which is useful after you rotate the key or change the account's roles.
| Service | Scope |
|---|---|
| Firebase Cloud Messaging | SCOPE_FCM |
| Cloud Storage | SCOPE_STORAGE |
| Most other Google Cloud APIs | SCOPE_CLOUD, or the API's own scope string |
Types
ServiceAccount
struct ServiceAccount| Name | Type | Description |
|---|---|---|
client_email | str = "" | The account email. |
private_key | str = "" | The PEM private key. |
token_uri | str = "https://oauth2.googleapis.com/token" | The address the token comes from. |
project_id | str = "" | The project id. |
ok | bool = false | It was read correctly. |
import google
func main:
document := `{"type":"service_account","project_id":"salam-demo","client_email":"bot@salam-demo.iam.gserviceaccount.com","private_key":"(the private key goes here)"}`
account := google.ParseServiceAccount(document)
println account.ok, account.project_id, account.client_email
println account.token_uri
println account.private_key.Len() > 0
println google.ParseServiceAccount(`{"project_id":"x"}`).ok
println google.Authorization("ya29.abc")
println google.SCOPE_FCM
println google.SCOPE_STORAGE
println google.SCOPE_CLOUD
endConstants and variables
SCOPE_FCM
const SCOPE_FCM: str = "https://www.googleapis.com/auth/firebase.messaging"The example for this item is shown with the ones above: google-Account.salam
SCOPE_STORAGE
const SCOPE_STORAGE: str = "https://www.googleapis.com/auth/devstorage.read_write"The example for this item is shown with the ones above: google-Account.salam
SCOPE_CLOUD
const SCOPE_CLOUD: str = "https://www.googleapis.com/auth/cloud-platform"The example for this item is shown with the ones above: google-Account.salam
Functions
ParseServiceAccount
func ParseServiceAccount(document: str): ServiceAccountclient_email or private_key is missing, the result has ok false. token_uri keeps its default when the file has none.The example for this item is shown with the ones above: google-Account.salam
AccessToken
func AccessToken(sa: ServiceAccount, scope: str, ok &: bool): strok to false and gives no reason.import google
import io
import net.http
func main:
account := google.ParseServiceAccount(io.ReadFile("service-account.json"))
if not account.ok:
println "the service account file is not valid"
ret
end
mut good := false
token := google.AccessToken(account, google.SCOPE_STORAGE, good)
if not good:
println "the token was not granted"
ret
end
mut headers := http.NewHeaders()
headers.Insert("Authorization", google.Authorization(token))
r := http.GetWith("https://storage.googleapis.com/storage/v1/b?project=" + account.project_id, headers)
println http.Status(r)
google.Forget(account)
endForget
func Forget(sa: ServiceAccount)The example for this item is shown with the ones above: google-Token.salam
Authorization
func Authorization(token: str): strAuthorization header with the token.The example for this item is shown with the ones above: google-Account.salam