Integrate Unkey to your API for managing call quotas. With usage-limited keys, this API enables you to control access while implementing automatic refill strategies—daily or monthly—ensuring seamless user experiences without exceeding limits.
Quota limiting for APIs is essential for preventing abuse, managing costs, ensuring fair access, optimizing performance, and upholding security and compliance.
This template showcases a generative AI REST API built with Rust and Rocket web framework. It demonstrates a secure method for storing created API keys using HTTP-only cookies. The /generate-image endpoint accepts a prompt message as payload, verifies the API key (decrementing remaining credits), and requests images from OpenAI. If the key becomes invalid, the user receives an error message indicating that the quota has been exceeded.
- Go to /settings/root-keys and click on the "Create New Root Key" button.
- Enter a name for the key.
- Select the following workspace permissions:
create_key,read_key,encrypt_keyanddecrypt_key. - Click "Create".
- Go to https://app.unkey.com/apis and click on the "Create New API" button.
- Give it a name.
- Click "Create".
- Go to the https://platform.openai.com/ and create an account or log in.
- Navigate to the API section in your dashboard.
- Click on “Create API Key” or “Generate API Key.”
- Copy and securely store the generated key.
- Clone the repository to your local machine:
git clone [email protected]:unrenamed/unkey-rust-rocket
cd unkey-rust-rocket- Create a
.envfile in the root directory and populate it with the following environment variables:
OPENAI_API_KEY=your-openai-api-key
UNKEY_ROOT_KEY=your-unkey-root-key
UNKEY_API_ID=your-unkey-api-idEnsure you replace your-* with your actual Unkey credentials.
- Start the server:
cargo runThe server will start and listen on the port specified in the .env file (default is 8000).
- Use
/authorizeroute to generate a new API key which will be saved to cookies:
curl -X POST http://localhost:8000/authorize- Use
/meroute to ensure you've successfully authorized:
curl http://localhost:8000/me- Send a prompt message to
/generate-imageroute to receive a URL to the generated image:
curl -X POST http://localhost:8000/generate_image \
-H "Content-Type: application/json" \
-d '{"prompt": "A sunset over a mountain range"}'