stack/docs/templates-python/authentication/api-setup.mdx
2025-06-27 11:54:59 -05:00

166 lines
5.0 KiB
Plaintext

---
title: API Setup & Configuration
---
This guide covers the essential setup for using Stack Auth's REST API in your Python application. Stack Auth provides a REST API for managing users, sessions, and authentication flows.
## Prerequisites
Before you begin, make sure you have:
- A Stack Auth [project](https://app.stack-auth.com/projects) created
- Python 3.7+ installed
- `requests` library (`pip install requests`)
## Environment Configuration
First, set up your API credentials. Get these from your Stack Auth dashboard:
```bash
# .env file
STACK_PROJECT_ID=your_project_id
STACK_PUBLISHABLE_KEY=your_publishable_key
STACK_SECRET_KEY=your_secret_key
STACK_API_URL=https://api.stack-auth.com
```
## Basic API Client Setup
Create a basic API client to handle Stack Auth requests:
```python
import os
import requests
from typing import Dict, Any, Optional
class StackAuthClient:
def __init__(self):
self.project_id = os.getenv('STACK_PROJECT_ID')
self.secret_key = os.getenv('STACK_SECRET_KEY')
self.publishable_key = os.getenv('STACK_PUBLISHABLE_KEY')
self.api_url = os.getenv('STACK_API_URL', 'https://api.stack-auth.com')
if not all([self.project_id, self.secret_key]):
raise ValueError("Missing required Stack Auth credentials")
def _make_request(
self,
method: str,
endpoint: str,
data: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None
) -> requests.Response:
"""Make authenticated request to Stack Auth API"""
url = f"{self.api_url}/api/v1{endpoint}"
# Add authentication headers
auth_headers = {
'X-Stack-Project-Id': self.project_id,
'X-Stack-Secret-Key': self.secret_key,
'Content-Type': 'application/json'
}
if headers:
auth_headers.update(headers)
response = requests.request(
method=method,
url=url,
json=data,
headers=auth_headers
)
# Handle common error cases
if response.status_code == 401:
raise Exception("Authentication failed - check your API credentials")
elif response.status_code == 403:
raise Exception("Forbidden - insufficient permissions")
elif not response.ok:
raise Exception(f"API request failed: {response.status_code} - {response.text}")
return response
def get(self, endpoint: str, **kwargs) -> requests.Response:
return self._make_request('GET', endpoint, **kwargs)
def post(self, endpoint: str, data: Dict[str, Any] = None, **kwargs) -> requests.Response:
return self._make_request('POST', endpoint, data, **kwargs)
def put(self, endpoint: str, data: Dict[str, Any] = None, **kwargs) -> requests.Response:
return self._make_request('PUT', endpoint, data, **kwargs)
def delete(self, endpoint: str, **kwargs) -> requests.Response:
return self._make_request('DELETE', endpoint, **kwargs)
# Initialize the client
stack_client = StackAuthClient()
```
## Testing Your Setup
Test your API connection with a simple request:
```python
def test_connection():
try:
# Test with a simple API call
response = stack_client.get('/users')
print("✅ Connection successful!")
print(f"Found {len(response.json().get('users', []))} users")
return True
except Exception as e:
print(f"❌ Connection failed: {e}")
return False
# Run the test
if __name__ == "__main__":
test_connection()
```
## Error Handling
Implement proper error handling for production use:
```python
import logging
from typing import Optional
logger = logging.getLogger(__name__)
class StackAuthError(Exception):
"""Base exception for Stack Auth errors"""
pass
class StackAuthClient:
# ... previous code ...
def safe_request(
self,
method: str,
endpoint: str,
data: Optional[Dict[str, Any]] = None
) -> Optional[Dict[str, Any]]:
"""Make a safe request with comprehensive error handling"""
try:
response = self._make_request(method, endpoint, data)
return response.json()
except requests.exceptions.ConnectionError:
logger.error("Failed to connect to Stack Auth API")
raise StackAuthError("Network connection failed")
except requests.exceptions.Timeout:
logger.error("Request to Stack Auth API timed out")
raise StackAuthError("Request timed out")
except Exception as e:
logger.error(f"Stack Auth API error: {e}")
raise StackAuthError(f"API request failed: {e}")
```
## Next Steps
With your API client set up, you can now:
- [Authenticate users](./user-sessions) with your application
- [Handle OAuth flows](./oauth-flows) for social login
- [Validate server-side sessions](./server-validation)
For detailed API reference, see the [REST API documentation](/api/overview).