Public API
This guide will walk you through implementing Public APIs in your SaaS using the built-in API Key infrastructure. This infrastructure allows users to securely expose their API endpoints, ensuring that only authenticated requests can access their organization's data.
API Key Infrastructure
The API Key infrastructure allows each organization to generate and manage its own API keys, which are used to authenticate requests. These keys are unique to each organization and must be included in the request headers for authorized access.
How It Works
To create an API key for organization, follow these steps:
- Generate API Keys: Each organization can generate API keys through the API Key section.
- Secure Access: API keys must be passed in the request headers to access public APIs.
- Key Validation: API keys are validated via the
getOrganizationAPIKeyData
function, ensuring that only authorized users can access the organization's data.
API Security
To protect your API endpoints from unauthorized access, you must validate the incoming API key before processing the request. Use the getOrganizationAPIKeyData
function, which checks the x-api-key
header, verifies its existence, and ensures the key is valid.
The getOrganizationAPIKeyData
function fetches and verifies the API key from the headers, ensuring the key belongs to an active organization.
How to Use It
To secure your API routes, simply add the getOrganizationAPIKeyData
function at the top of your API handler. It checks the x-api-key header, retrieves the corresponding organization data, and ensures the key is valid.
Example of securing an API route:
How the Function Works
The function retrieves the x-api-key from the request headers.
- It validates the API key by checking its existence in the
organization_apikeys
table in Supabase. - If the key is valid, it returns the associated organization's data.
- If the key is invalid or missing, an error is thrown, preventing unauthorized access.
- The last usage timestamp is updated via the
update_api_key_last_used
Supabase function to track API key usage.
Conclusion
By integrating the getOrganizationAPIKeyData
function, you can securely expose public APIs for your SaaS product using API keys. This ensures that only authorized users with valid API keys can access sensitive organizational data.