py-vapid is a Python library designed for generating VAPID (Voluntary Application Server Identification) headers, essential for authenticating Web Push notifications. It allows for the creation of VAPID key sets and the signing of JWT claims to identify the push service sender. As of its current version 1.9.4, the library is actively maintained with regular updates.
pip install py-vapidVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to generate a VAPID key pair using `Vapid01`, and then use the private key to sign a set of VAPID claims, producing the necessary `Authorization` and `Crypto-Key` HTTP headers for Web Push notifications. Keys are generated in memory for demonstration, but in a production environment, they should be securely stored and loaded. Essential claims like `sub` (sender email) and `aud` (push service audience) are highlighted.
Ensure that your VAPID claims dictionary always includes an 'aud' key with the appropriate push service endpoint origin (e.g., `https://fcm.googleapis.com` or `https://updates.push.services.mozilla.com`).
Always prepend `mailto:` to the email address when setting the `sub` claim. Example: `{'sub': 'mailto:developer@example.com'}`.Explicitly set the `exp` claim to a Unix timestamp within 24 hours from the current time, preferably shorter, for enhanced security. For example: `int(time.time()) + 12 * 60 * 60` for 12 hours.
Utilize the built-in `Vapid01.from_pem()`, `Vapid01.from_der()`, or `Vapid01.from_raw()` methods for loading keys from various formats, as they handle the underlying cryptographic library's requirements. When encoding/decoding, ensure consistent handling of base64 padding or use utility functions that specifically handle URL-safe encoding without padding.
You need to create an instance of the `Vapid` class first and then call the method on that instance. For example, `from py_vapid import Vapid; vapid_obj = Vapid(); headers = vapid_obj.sign(claims)` or `vapid_obj.generate_keys()`.
Ensure the private key string is a properly base64 URL-safe encoded value without incorrect padding. If the key is in PEM format, use `Vapid.from_pem()` instead. If it's a raw uncompressed private key, ensure it's correctly base64url-encoded for `from_raw()`.
Include a valid 'aud' field in your VAPID claims dictionary. The 'aud' value should be the scheme and host of the push service endpoint, e.g., `{'sub': 'mailto:user@example.com', 'aud': 'https://push.example.com', 'exp': 123456789}`.Install the library using pip: `pip install py-vapid`. Ensure you are running this command and your Python script in the same environment.