Skip to content

Commit

Permalink
added fastapi implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
rishabkumar7 committed Mar 7, 2024
1 parent 7c28771 commit c0bc820
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 26 deletions.
59 changes: 38 additions & 21 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
from flask import Flask, jsonify, render_template, request, send_from_directory
import random
import json
from fastapi import FastAPI, Request, HTTPException
from typing import Optional
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from azure.cosmos import CosmosClient
import os
from dotenv import load_dotenv
import random

load_dotenv()


#Initialize Flask
app = Flask(__name__)
# Initialize FastAPI
app = FastAPI()

# Initialize Cosmos Client
url = os.getenv("AZURE_COSMOSDB_URL")
Expand All @@ -28,33 +30,48 @@
documents = list(container.read_all_items())


templates = Jinja2Templates(directory="templates")

# Load Browser Favicon Icon
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico',mimetype='image/vnd.microsoft.icon')
app.mount("/static", StaticFiles(directory="static"), name="static")


@app.get('/', description="Return the home page with a random quote.")
async def home(request: Request):
"""
Return the home page with a random quote.
@app.route('/')
def home():
- **request**: The request object.
"""
random_document = random.choice(documents)
random_quote = random.choice(random_document['quotes'])
return render_template('index.html', quote=random_quote['quote'], author=random_quote['author'])
return templates.TemplateResponse('index.html', {"request": request, "quote": random_quote['quote'], "author": random_quote['author']})

@app.route('/api/random', methods=['GET'])
def get_quote():
@app.get('/api/random', description="Return a random quote.")
async def get_quote():
"""
Return a random quote.
This endpoint returns a random quote from the database in JSON format.
"""
# Select a random document
random_document = random.choice(documents)
# Select a random quote from the 'quotes' array in the document
random_quote = random.choice(random_document['quotes'])
return jsonify(random_quote), 200
return {"quote": random_quote['quote'], "author": random_quote['author']}


@app.get('/api/search', description="Search for quotes containing a specific word.")
async def search(word: Optional[str] = None):
"""
Search for quotes containing a specific word.
- **word**: The word to search for in the quotes.
@app.route('/api/search', methods=['GET'])
def search():
word = request.args.get('word', '')
This endpoint returns all quotes that contain the word in JSON format.
"""
if not word:
return jsonify({'response': 200, 'message': 'No word provided for search.'})
return HTTPException(status_code=400, detail="No word provided for search.")

# Query for all documents
documents = list(container.read_all_items())
Expand All @@ -63,9 +80,9 @@ def search():
matching_quotes = [quote for document in documents for quote in document['quotes'] if word.lower() in quote['quote'].lower()]

if not matching_quotes:
return jsonify({'response': 200, 'message': 'No quotes matched the query.'})
return {"response": 200, "message": "No quotes matched the query."}

return jsonify({'response': 200, 'results': matching_quotes})
return {"response": 200, "results": matching_quotes}


#Build Pagination endpoint
Expand Down
23 changes: 19 additions & 4 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
annotated-types==0.6.0
anyio==4.3.0
azure-core==1.30.0
azure-cosmos==4.5.1
blinker==1.6.2
certifi==2024.2.2
charset-normalizer==3.3.2
click==8.1.3
colorama==0.4.6
exceptiongroup==1.2.0
Flask==2.3.2
fastapi==0.110.0
h11==0.14.0
idna==3.6
importlib-metadata==6.6.0
iniconfig==2.0.0
itsdangerous==2.1.2
Expand All @@ -11,11 +19,18 @@ jsonify==0.5
MarkupSafe==2.1.3
packaging==23.2
pluggy==1.4.0
pydantic==2.6.3
pydantic-core==2.16.3
pytest==8.0.2
pytest-flask==1.3.0
python-dotenv==1.0.1
requests==2.31.0
six==1.16.0
sniffio==1.3.1
starlette==0.36.3
tomli==2.0.1
typing-extensions==4.10.0
urllib3==2.2.1
uvicorn==0.27.1
Werkzeug==2.3.6
zipp==3.15.0
azure-cosmos==4.5.1
python-dotenv==1.0.1

2 changes: 1 addition & 1 deletion templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<meta name="description" content="The very best Stoic quotes from the three great Roman Stoics: Marcus Aurelius, Seneca, and Epictetus.">
<meta name="keywords" content="Stoic, Stoicism, Quotes, Stoic Quotes API">
<meta name="author" content="Rishab Kumar">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
<link id="favicon" rel="icon" type="image/x-icon" href="static/favicon.ico">
<style>
body {
background-color: #000;
Expand Down

0 comments on commit c0bc820

Please sign in to comment.