page_shot / HF_SPACES_ENV_GUIDE.md
CatPtain's picture
Upload 4 files
0dbbe1c verified
# Hugging Face Spaces Environment Variable Setup Guide
## πŸ” API Key Authentication Setup
This Space supports API key authentication through environment variables. Follow these steps to enable secure access:
### 1. Set Environment Variable in Space Settings
1. **Go to your Space settings:**
- Navigate to your Space on Hugging Face
- Click on the "Settings" tab
- Scroll down to "Repository secrets" or "Environment variables" section
2. **Add the API_KEY variable:**
- **Name:** `API_KEY`
- **Value:** Your secure API key (e.g., `sk-1234567890abcdef...`)
- Click "Add secret" or "Save"
3. **Restart your Space:**
- The Space will automatically restart when you add/modify environment variables
- Wait for the Space to rebuild and restart
### 2. Environment Variable Behavior
- **If API_KEY is set:** Authentication is required for the `/screenshot` endpoint
- **If API_KEY is not set:** Open access mode (no authentication required)
### 3. Using the API with Authentication
#### Option 1: Authorization Header
```bash
curl -X POST "https://your-space.hf.space/screenshot" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com"}'
```
#### Option 2: x-api-key Header
```bash
curl -X POST "https://your-space.hf.space/screenshot" \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com"}'
```
#### JavaScript Example
```javascript
const response = await fetch('/screenshot', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: 'https://example.com',
width: 1280,
height: 720
})
});
```
### 4. Security Best Practices
- **Generate a strong API key:** Use a cryptographically secure random string
- **Keep it secret:** Never expose the API key in client-side code or logs
- **Use HTTPS:** Always access the API over HTTPS in production
- **Rotate regularly:** Consider rotating the API key periodically
### 5. Testing Authentication
1. **Check authentication status:**
```bash
curl https://your-space.hf.space/
```
2. **Test with correct API key:**
```bash
curl -X POST "https://your-space.hf.space/screenshot" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com"}'
```
3. **Test without API key (should fail if authentication is enabled):**
```bash
curl -X POST "https://your-space.hf.space/screenshot" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com"}'
```
### 6. Error Responses
#### 401 Unauthorized (Missing or Invalid API Key)
```json
{
"error": "Unauthorized",
"message": "Valid API key required. Please provide API key in Authorization header or x-api-key header.",
"hint": "Use \"Authorization: Bearer YOUR_API_KEY\" or \"x-api-key: YOUR_API_KEY\""
}
```
### 7. Recommended API Key Format
Generate a secure API key using one of these methods:
#### Python
```python
import secrets
import string
def generate_api_key(length=32):
alphabet = string.ascii_letters + string.digits
return 'sk-' + ''.join(secrets.choice(alphabet) for _ in range(length))
api_key = generate_api_key()
print(f"Generated API Key: {api_key}")
```
#### Node.js
```javascript
const crypto = require('crypto');
function generateApiKey(length = 32) {
return 'sk-' + crypto.randomBytes(length).toString('hex').slice(0, length);
}
const apiKey = generateApiKey();
console.log(`Generated API Key: ${apiKey}`);
```
#### Online Generator
You can also use online tools like:
- `openssl rand -hex 32` (command line)
- Any secure random string generator
### 8. Demo Page Features
The demo page automatically detects whether authentication is enabled:
- **With API_KEY set:** Shows API key input field
- **Without API_KEY:** Shows open access message
- **Dynamic UI:** Adapts based on authentication status
### 9. Health Check Response Examples
#### Without API_KEY Environment Variable
```json
{
"message": "Page Screenshot API - Hugging Face Spaces",
"version": "1.4.0",
"authentication": {
"type": "Open Access (No API Key Set)",
"required": false,
"note": "Set API_KEY environment variable to enable authentication"
}
}
```
#### With API_KEY Environment Variable
```json
{
"message": "Page Screenshot API - Hugging Face Spaces",
"version": "1.4.0",
"authentication": {
"type": "API Key Required",
"required": true,
"note": "API key required for screenshot endpoint"
}
}
```
---
## πŸš€ Quick Setup Summary
1. Generate a secure API key: `sk-1234567890abcdef...`
2. Add `API_KEY` environment variable in Space settings
3. Set the value to your generated API key
4. Wait for Space to restart
5. Test with the demo page or API calls
Your Space is now secure and ready for production use! πŸ”
## πŸ”„ Environment Variable Management
- **Add Variable:** Space Settings β†’ Environment Variables β†’ Add `API_KEY`
- **Update Variable:** Modify the value and save (Space will restart)
- **Remove Variable:** Delete the variable to disable authentication
- **View Status:** Check `/` or `/status` endpoints for current auth status
## πŸ“± Integration Examples
### Frontend JavaScript
```javascript
// Store API key securely (never in source code)
const API_KEY = localStorage.getItem('screenshot_api_key');
async function takeScreenshot(url) {
const response = await fetch('/screenshot', {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ url })
});
if (response.ok) {
return await response.blob();
} else {
const error = await response.json();
throw new Error(error.message);
}
}
```
### Backend Integration
```javascript
// Express.js middleware for API key validation
const SCREENSHOT_API_KEY = process.env.SCREENSHOT_API_KEY;
async function screenshotMiddleware(req, res, next) {
try {
const response = await fetch('https://your-space.hf.space/screenshot', {
method: 'POST',
headers: {
'Authorization': `Bearer ${SCREENSHOT_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(req.body)
});
if (response.ok) {
const screenshot = await response.buffer();
res.set('Content-Type', 'image/jpeg');
res.send(screenshot);
} else {
res.status(response.status).json(await response.json());
}
} catch (error) {
res.status(500).json({ error: error.message });
}
}
```