DeveloperBreeze

Machine Learning With Fastapi Development Tutorials, Guides & Insights

Unlock 1+ expert-curated machine learning with fastapi tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your machine learning with fastapi skills on DeveloperBreeze.

Building AI-Powered Web Apps with Python and FastAPI

Tutorial October 22, 2024
python

We will serve a basic HTML page that allows users to input text and see the results.

   from fastapi.responses import HTMLResponse

   @app.get("/", response_class=HTMLResponse)
   def home():
       html_content = """
       <html>
           <head>
               <title>AI Sentiment Analysis</title>
           </head>
           <body>
               <h1>Enter text for Sentiment Analysis</h1>
               <form action="/analyze/" method="post" id="form">
                   <textarea name="text" rows="4" cols="50"></textarea><br>
                   <button type="submit">Analyze</button>
               </form>
               <div id="result"></div>

               <script>
                   const form = document.getElementById('form');
                   form.addEventListener('submit', async (e) => {
                       e.preventDefault();
                       const formData = new FormData(form);
                       const response = await fetch('/analyze/', {
                           method: 'POST',
                           body: JSON.stringify({ text: formData.get('text') }),
                           headers: {
                               'Content-Type': 'application/json'
                           }
                       });
                       const result = await response.json();
                       document.getElementById('result').innerText = 'Sentiment: ' + result.sentiment.label;
                   });
               </script>
           </body>
       </html>
       """
       return HTMLResponse(content=html_content)