A simple API for generating short stories using OpenAI's GPT-3.5 model. The API accepts keywords and generates engaging stories suitable for young readers.
- Generate stories using predefined keywords
- Random keyword generation if none provided
- Story caching to avoid duplicate API calls
- Input validation and sanitization
- Customizable character name and age
- Health check endpoint
- Available keywords endpoint
- Bun installed
- OpenAI API key
- Clone the repository:
git clone <your-repo-url>
cd story-generator-api- Install dependencies:
bun install- Create a
.envfile in the root directory:
OPENAI_API_KEY=your_api_key_hereDevelopment mode:
bun run devProduction mode:
bun run startGenerate a new story using provided keywords or random keywords.
Request Body:
{
"keywords": ["Minecraft", "magic"], // Optional
"name": "Alex", // Optional
"age": 10 // Optional
}Parameters:
keywords: Array of keywords to use in the story (optional)- If not provided, random keywords will be selected
- Must be from the available keywords list
name: Character's name (optional)- Must contain at least one alphabetic character
- Non-alphabetic characters will be removed
- Only the first word will be used
age: Character's age (optional)- Must be a positive integer between 1 and 16
Response:
{
"story": "Once upon a time...",
"keywords_used": ["Minecraft", "magic"],
"cached": false
}Get all available keywords organized by categories.
Response:
{
"categories": {
"games": ["Minecraft", "Roblox", "Fortnite", "Among Us"],
"characters": ["boy", "girl", "wizard", "warrior", "explorer"],
"elements": ["magic", "adventure", "mystery", "friendship"],
"settings": ["castle", "forest", "space", "underwater"]
},
"total_keywords": 17
}Check the API health status.
Response:
{
"status": "ok",
"cache_size": 5
}This application can be deployed to various platforms:
# Install Fly CLI
curl -L https://fly.io/install.sh | sh
# Login to Fly
fly auth login
# Deploy
fly launch
fly deploy- Connect your GitHub repository
- Create new project from GitHub
- Add environment variables
- Deploy automatically
OPENAI_API_KEY: Your OpenAI API keyPORT: Server port (default: 3000)
Using GPT-3.5-turbo-instruct model:
- Cost per 1K tokens: $0.0015
- Average story cost: ~$0.00045 (300 tokens)
- Caching helps reduce costs for repeated requests
The API returns appropriate error messages for invalid inputs:
{
"error": "Invalid keywords provided",
"invalidKeywords": ["InvalidKeyword1", "InvalidKeyword2"],
"message": "Please use only keywords from the available list. Use GET /keywords to see all available options."
}{
"error": "Invalid name",
"message": "Name must contain at least one alphabetic character"
}{
"error": "Invalid age",
"message": "Age must be a positive integer between 1 and 16"
}- Fork the repository
- Create your feature branch
- Commit your changes
- Push to the branch
- Create a new Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.