Creating an Interactive Web Page with the Gemini API: A Step-by-Step Guide

In the vast realm of artificial intelligence, the Gemini API stands out as a powerful tool for content generation. With its capabilities, developers

Detailed Report on the Gemini API HTML Demo

In the vast realm of artificial intelligence, the Gemini API stands out as a powerful tool for content generation. With its capabilities, developers can create innovative solutions to automate content creation tasks. In this article, we delve into a practical demonstration of the Gemini API through a web-based application. Let's explore how this code snippet harnesses the potential of AI to generate content effortlessly.

Understanding the Code Structure

HTML Structure

The HTML structure provides the foundation for our web application. It includes essential elements such as text areas for user input, buttons for triggering actions, and containers for displaying results.
  • <!DOCTYPE html>: Declares the document type and version of HTML used.
  • <html lang="en">: Specifies the language of the document.
  • <head>: Contains meta-information about the document and links to external resources like stylesheets and scripts.
  • <body>: The main content area visible to users.
Here is a picece of code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gemini API Demo</title>
</head>
<body>
    <div class="container">
        <h1>Gemini API Demo</h1>
        <textarea id="prompt" placeholder="Enter your prompt here..."></textarea>
        <button onclick="generateContent()">Generate Content</button>
        <div class="result" id="result"></div>
        <div class="best-keywords hidden" id="bestKeywords">
            <h2>Best Keywords for Your Post</h2>
            <ul id="keywordsList"></ul>
        </div>
    </div>
</body>
</html>
<style>
    body {
        font-family: Arial, sans-serif;
        background-color: #f4f4f4;
        margin: 0;
        padding: 0;
    }
    .container {
        max-width: 800px;
        margin: 50px auto;
        padding: 20px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    /* ... */
</style>
<script>
    function generateContent() {
        const prompt = document.getElementById('prompt').value;
        const apiKey = "AIzaSyBLiV5x_lyqN2fP0A4qOrzc6J2bTdI8GT8";
        const apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=" + apiKey;
        const requestBody = {
            contents: [
                {
                    parts: [
                        { text: prompt }
                    ]
                }
            ]
        };

        fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(requestBody),
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch data from Gemini API');
            }
            return response.json();
        })
        .then(data => {
            const generatedContent = data.candidates[0].content.parts[0].text;
            const keywords = generatedContent.split('\n').filter(keyword => keyword !== '*' && keyword !== ''); // Filter out asterisks and empty cells
            const resultContainer = document.getElementById('result');
            resultContainer.innerHTML = '';
            keywords.forEach(keyword => {
                const keywordElement = document.createElement('div');
                keywordElement.classList.add('keyword');

                const keywordText = document.createElement('span');
                keywordText.classList.add('keyword-text');
                keywordText.textContent = keyword;

                const copyButton = document.createElement('button');
                copyButton.textContent = 'Copy';
                copyButton.classList.add('copy-button');
                copyButton.addEventListener('click', () => {
                    copyToClipboard(keyword);
                });

                keywordElement.appendChild(keywordText);
                keywordElement.appendChild(copyButton);

                resultContainer.appendChild(keywordElement);
            });

            // Show best keywords section
            const bestKeywordsContainer = document.getElementById('bestKeywords');
            bestKeywordsContainer.classList.remove('hidden');
            const keywordsList = document.getElementById('keywordsList');
            keywordsList.innerHTML = '';
            keywords.slice(0, 5).forEach(keyword => {
                const listItem = document.createElement('li');
                listItem.textContent = keyword;
                keywordsList.appendChild(listItem);
            });
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('result').textContent = 'Error: Failed to generate content';
        });
    }

    function copyToClipboard(text) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        alert('Copied to clipboard: ' + text);
    }
</script>

Click here to get the full source code
Source Code 5.94kb


CSS Styling

The CSS styling enhances the visual appeal and user experience of the application. It defines the layout, colors, and typography used throughout the interface.

  • .container: Styles the main content container with a maximum width, margin, padding, and background color.
  • textarea and button: Defines styles for user input elements like text areas and buttons.
  • .keyword and .copy-button: Styles for displaying generated keywords and copy buttons.

JavaScript Functionality

The JavaScript code adds interactivity to the web application by handling user input, making API requests, and updating the UI with generated content.

  • generateContent() Function: Retrieves user input, constructs an API request, sends it to the Gemini API, and updates the UI with the generated content.
  • copyToClipboard() Function: Copies text to the clipboard when the user clicks the copy button associated with each generated keyword.

Key Features and Functionality

Content Generation

The generateContent() function orchestrates the content generation process. It collects user input, constructs a request payload, sends it to the Gemini API endpoint, and processes the response to display generated content.

API Integration

The application leverages the Gemini API to generate content dynamically. It sends HTTP requests to the API endpoint with the necessary parameters and handles the response to extract generated content and keywords. 

How to get free api

  • Search for Free APIs: Look for APIs that offer free access. Websites like RapidAPI, ProgrammableWeb, and Public APIs list various APIs categorized by type, and many of them offer free plans click herehere.
  • Read Documentation: Once you find an API that interests you, read its documentation thoroughly to understand its capabilities, limitations, and pricing plans. Look for information about their free tier, usage limits, and any restrictions.
  • Sign Up for an Account: Create an account on the API provider's website. Some APIs require registration before you can access their documentation or obtain an API key.
  • Get API Key: After signing up, you may need to generate an API key. This key is typically used to authenticate your requests to the API server.
  • Understand Usage Limits: Free plans often come with usage limits, such as a maximum number of requests per day or per month. Make sure you understand these limits to avoid unexpected charges or service interruptions.
  • Explore Examples: Many API providers offer example code and tutorials to help you get started. Take advantage of these resources to learn how to use the API effectively.
  • Test Your Integration: Before using the API in a production environment, test your integration thoroughly to ensure it meets your needs and works as expected.

Keyword Extraction

After receiving the generated content from the API, the application extracts keywords for further analysis. It filters out irrelevant elements and displays the extracted keywords to the user, facilitating content refinement and optimization.

User Interaction

The interface allows users to interact with the generated content by copying keywords to the clipboard with a single click. This feature enhances usability and streamlines the content creation process.

Conclusion

The Gemini API demo showcased in this article exemplifies the fusion of artificial intelligence and web development. By harnessing the power of AI-driven content generation, developers can create innovative solutions to automate repetitive tasks and unleash creativity. As AI continues to evolve, applications like this serve as a testament to the boundless possibilities of technology in shaping the future of content creation. Whether you're a developer exploring new frontiers or a content creator seeking efficiency, the Gemini API offers a glimpse into the exciting possibilities that lie ahead.

Stay tuned for more insights and updates on AI-driven technologies and their impact on various industries.