Skip to content

0xAhmadYousuf/Flask-Movie-API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

image

Flask-Movie-API

Movie Rating System API Documentation

এই প্রোজেক্ট টা মজার একটা প্রোজেক্ট ছিল, যেটাতে সময় কাটাতে যেমন মজা লেগেছে তেমন ফ্লাস্ক দিয়ে প্র্যক্টিক্যল একটা কাজ ও হয়েছে, তবে জ্যন্গো ইউজ করা হয়নি বিধায় লাইট এবং ইজি হয়েছে কোড, আর এতে আমার বানানো দুটা লাইব্রেরী Hash2603 এবং MailUserVerify ব্যবহার করে এর মধ্যে কিছু অতিরিক্ত ফিচার এনেছি ( আর সত্যি বলতে চার ঘন্টা সময়ে এতটুকু করতে পেরেছি ) যাইহোক, Visionary Tech Solution এর ইন্টারভিউ মূলক এই কাজটা সকলের জন্য ওপেন সোর্স কপিরাইট ফ্রি, ( লাইব্রেরি দুটা এর অন্তর্ভুক্ত নয় )

Language and Database

  • Language: Python
  • Database: JSON files (users.json, movies.json, ratings.json)
  • Reason: JSON files are used as a simple and lightweight solution for storing user, movie, and rating data. They provide easy readability and flexibility, making them suitable for this project's requirements.

Project Repository

  • You can find the project repository at Flask-Movie-API. It's a Flask-based implementation of a Movie API with similar functionalities.

Setup Instructions

  1. Ensure you have Python installed on your system.
  2. Clone or download the project repository from GitHub.
  3. Install required dependencies by running pip install -r requirements.txt.
  4. Run the Flask development server using python manage.py runserver.
  5. The API will be accessible at http://localhost:5000.

Assumptions

  • User IDs start from 1 and increment sequentially.
  • User authentication is based on email and password combination.
  • Each movie and user rating is associated with a unique identifier, and IDs increment sequentially.
  • The system uses a simple hash-based authentication mechanism for generating and verifying keys.

Problem Solving

  • Implemented Features:
    • User registration (/signup endpoint)
    • User authentication (/login endpoint)
    • Adding movies to the database (/add_movie endpoint)
    • Retrieving a list of all movies (/movies endpoint)
    • Rating movies (/rate_movie endpoint)
    • Searching for movies by name (/search_movie endpoint)
    • Error handling using decorators (@error_handler)
  • Remaining Tasks:
    • Implementing login functionality.
    • Adding error handling and validation for different endpoints.
    • Enhancing security measures such as password hashing.
    • Improving efficiency and scalability of the database operations.

Problems Faced and Solutions

  • Problem: Need to handle errors and exceptions uniformly across different endpoints.

    • Solution: Implemented a decorator @error_handler to catch and handle exceptions gracefully, providing consistent error responses.
  • Problem: Ensuring uniqueness of user email addresses and preventing duplicate entries.

    • Solution: Added logic to check for existing email addresses during user registration and return appropriate error messages if duplication is detected.
  • Problem: Generating and validating keys for user authentication.

    • Solution: Created functions key_maker() and key_check() to generate and verify keys based on user email and password combinations. This ensures secure authentication and authorization.
  • Problem: Handling user input validation and ensuring completeness of required fields.

    • Solution: Implemented checks to validate input data for user registration and movie addition endpoints, ensuring that essential fields are provided and not left blank.

Problems not solved till now

  • Database Updating Functionality: The current implementation lacks functions for updating existing data in the database, such as editing or deleting user profiles, movies, or ratings. This limitation means that any changes or corrections to user information, movie details, or ratings must be made manually by directly modifying the JSON files. Adding update functionality would enhance the API's usability and allow for more dynamic management of data without requiring manual intervention.

  • Data Checking for Ratings and Movies: There's a need to implement validation checks to ensure that duplicate ratings for the same movie by the same user are not allowed, and that movies being rated actually exist in the database. Without these checks, there's a risk of inconsistent data or errors occurring due to attempts to rate non-existent movies. Incorporating checks to verify the existence of movies and prevent duplicate ratings would improve the reliability and accuracy of the rating system within the API.

File Structure

flaskapp.
project_root/
______________________________________________________________________________________
  ├── UMODULES/
  │   ├── __pycache__/  # Contains bytecode-compiled files generated by Python
  │   │   ├── hash2603.cpython-311.pyc
  │   │   └── mailuserverify.cpython-311.pyc
  │   ├── hash2603.py
  │   └── mailuserverify.py
  ├── DB/
  │  ├── movies.json  # JSON file storing movie data
  │  ├── ratings.json  # JSON file storing movie ratings data
  │  └── users.json  # JSON file storing user data
  │
  ├── README.md  # Optional file containing project documentation
  ├── requirements.txt  # Optional file containing project modules list to install
  ├── flaskapp.py  # Main Flask application file
  └── flasktest.py  # Potentially for unit testing using Flask's built-in testing features


Routes

The following routes are available in the API:

  • POST /signup: Register a new user.
  • POST /login: Authenticate a user.
  • POST /add_movie: Add a new movie to the database.
  • GET /movies: Retrieve a list of all movies.
  • POST /rate_movie: Rate a movie.
  • GET /search_movie?name={movie_name}: Search for movies by name.

For more details on each endpoint and their usage, refer to the help message provided at the root endpoint (/).


Incomplete Feature: GitHub JSON Database Handler

To enhance the functionality of your project, consider adding a feature to interact with JSON files stored in a GitHub repository. The GitHubDBHandler class provided below allows you to load and write JSON files directly from a GitHub repository.

import json
import requests

class GitHubDBHandler:
    def __init__(self, repo_owner, repo_name, branch='main'):
        self.repo_owner = repo_owner
        self.repo_name = repo_name
        self.branch = branch
        self.base_url = f'https://raw.githubusercontent.com/{repo_owner}/{repo_name}/{branch}/'

    def load_file(self, file_path):
        try:
            url = self.base_url + file_path
            response = requests.get(url)
            if response.status_code == 200:
                return json.loads(response.text)
            else:
                print(f"Failed to load file: {file_path}. Status code: {response.status_code}")
        except Exception as e:
            print(f"Error loading file: {file_path}. {str(e)}")

    def write_file(self, file_path, data):
        try:
            url = self.base_url + file_path
            response = requests.put(url, json=data)
            if response.status_code == 200:
                print(f"File {file_path} updated successfully.")
            else:
                print(f"Failed to update file: {file_path}. Status code: {response.status_code}")
        except Exception as e:
            print(f"Error updating file: {file_path}. {str(e)}")

Usage example:

# Initialize the GitHubDBHandler with your GitHub repository details
db_handler = GitHubDBHandler(repo_owner='owner_username', repo_name='repository_name')

# Load JSON file from the repository
data = db_handler.load_file('path/to/file.json')

# Manipulate the data as needed

# Write the updated data back to the repository
db_handler.write_file('path/to/file.json', data)

Replace 'owner_username', 'repository_name', and 'path/to/file.json' with your GitHub repository details and the path to the JSON file you want to interact with.

This feature adds the capability to read and write JSON files stored in a GitHub repository directly from your Python code. Keep in mind to handle authentication if your repository is private and requires authentication to access its contents.


Feel free to explore the Flask-Movie-API repository for further insights into a Flask-based implementation of a similar Movie API! If you have any questions or need assistance, don't hesitate to ask.