diff --git a/mflix/README-PYTHON-FASTAPI.md b/mflix/README-PYTHON-FASTAPI.md index 229462f..8225b9a 100644 --- a/mflix/README-PYTHON-FASTAPI.md +++ b/mflix/README-PYTHON-FASTAPI.md @@ -1,22 +1,202 @@ # Python FastAPI MongoDB Sample MFlix Application -[TODO: Add intro] +This is a full-stack movie browsing application built with Python FastAPI and Next.js, demonstrating MongoDB operations using the `sample_mflix` dataset. The application showcases CRUD operations, aggregations, and MongoDB Search using the PyMongo driver. + +## Project Structure ``` ├── README.md -├── client/ # Next.js frontend -└── server/ # Python FastAPI backend +├── client/ # Next.js frontend (TypeScript) +└── server/ # Python FastAPI backend + ├── src/ + ├── tests/ + ├── .env.example + ├── main.py + ├── pytest.ini + ├── requirements.in + └── requirements.txt ``` +## Prerequisites + +- **Python 3.10** to **Python 3.13** +- **Node.js 20** or higher +- **MongoDB Atlas cluster or local deployment** with the `sample_mflix` dataset loaded + - [Load sample data](https://www.mongodb.com/docs/atlas/sample-data/) +- **pip** for Python package management +- **Voyage AI API key** (For MongoDB Vector Search) + - [Get a Voyage AI API key](https://www.voyageai.com/) + ## Getting Started -[TODO: Add getting started instructions explaining how to set connection string, start server, start client, etc.] +### 1. Configure the Backend + +Navigate to the Python FastAPI server directory: + +```bash +cd server/ +``` + +Create a `.env` file from the example: + +```bash +cp .env.example .env +``` + +Edit the `.env` file and set your MongoDB connection string: + +```env +# MongoDB Configuration +MONGO_URI=mongodb+srv://:@.mongodb.net/sample_mflix?retryWrites=true&w=majority +MONGO_DB=sample_mflix + +# Voyage AI Configuration +# API key for Voyage AI embedding model (required for Vector Search) +VOYAGE_API_KEY=your_voyage_api_key + +# CORS Configuration +# Comma-separated list of allowed origins for CORS +CORS_ORIGINS=http://localhost:3000,http://localhost:8000 +``` + +**Note:** Replace `username`, `password`, and `cluster` with your actual MongoDB Atlas +credentials. + +Make a virtual environment: + +```bash +python -m venv .venv +``` + +Activate the virtual environment: + +```bash +source .venv/bin/activate +``` + +Install Python dependencies: + +```bash +pip install -r requirements.txt +``` + +### 2. Start the Backend Server + +From the `server/` directory, run: + +```bash +fastapi dev main.py --reload +``` + +The server will start on `http://localhost:8000`. You can verify it's running by visiting: +- API root: http://localhost:8000/api/movies +- API documentation (Swagger UI): http://localhost:8000/docs + +### 3. Configure and Start the Frontend + +Open a new terminal and navigate to the client directory: + +```bash +cd client +``` + +Install dependencies: + +```bash +npm install +``` + +Start the development server: + +```bash +npm run dev +``` + +The Next.js application will start on `http://localhost:3000`. + +### 4. Access the Application + +Open your browser and navigate to: +- **Frontend:** http://localhost:3000 +- **Backend API:** http://localhost:8000 +- **API Documentation:** http://localhost:8000/docs + +## Features + +- **Browse Movies:** View a paginated list of movies from the sample_mflix dataset +- **Search:** Full-text search using MongoDB Search +- **Vector Search:** Semantic search using MongoDB Vector Search with Voyage AI embeddings +- **Filter:** Filter movies by genre, year, rating, and more +- **Movie Details:** View detailed information about each movie +- **Aggregations:** Complex data aggregations and analytics + +## Development + +### Backend Development + +The Python FastAPI backend uses: +- **FastAPI** for REST API framework +- **PyMongo** for database operations +- **Voyage AI** for vector embeddings +- **fastapi** for ASGI server + +To run all tests: + +```bash +cd server/ +source .venv/bin/activate # or `.venv\Scripts\activate` on Windows +pytest tests/ -v +``` + +### Frontend Development + +The Next.js frontend uses: +- **React 19** with TypeScript +- **Next.js 16** with App Router +- **Turbopack** for fast development builds + +#### Development Mode + +For active development with hot reloading and fast refresh: + +```bash +cd client +npm run dev +``` + +This starts the development server on `http://localhost:3000` with Turbopack for fast rebuilds. + +#### Production Build + +To create an optimized production build and run it: + +```bash +cd client +npm run build # Creates optimized production build +npm start # Starts production server +``` + +The production build: +- Minifies and optimizes JavaScript and CSS +- Optimizes images and assets +- Generates static pages where possible +- Provides better performance for end users + +#### Linting + +To check code quality: + +```bash +cd client +npm run lint +``` ## Issues If you have problems running the sample app, please check the following: - [ ] Verify that you have set your MongoDB connection string in the `.env` file. +- [ ] Verify that you have created and activated a Python `.venv` on Python v3.10 through v3.13. - [ ] Verify that you have started the Python FastAPI server. - [ ] Verify that you have started the Next.js client. - [ ] Verify that you have no firewalls blocking access to the server or client ports. @@ -24,3 +204,4 @@ If you have problems running the sample app, please check the following: If you have verified the above and still have issues, please [open an issue](https://github.com/mongodb/docs-sample-apps/issues/new/choose) on the source repository `mongodb/docs-sample-apps`. + diff --git a/mflix/server/python-fastapi/.env.example b/mflix/server/python-fastapi/.env.example index 7303405..e25ebf9 100644 --- a/mflix/server/python-fastapi/.env.example +++ b/mflix/server/python-fastapi/.env.example @@ -1,5 +1,5 @@ # MongoDB Configuration -MONGO_URI="mongodb://localhost:27017" +MONGO_URI="mongodb+srv://:@.mongodb.net/sample_mflix?retryWrites=true&w=majority" MONGO_DB="sample_mflix" # Voyage AI Configuration @@ -8,4 +8,4 @@ VOYAGE_API_KEY=your_voyage_api_key # CORS Configuration # Comma-separated list of allowed origins for CORS -CORS_ORIGINS="http://localhost:3000,http://localhost:3001" \ No newline at end of file +CORS_ORIGINS="http://localhost:3000,http://localhost:8000" \ No newline at end of file diff --git a/mflix/server/python-fastapi/README_OLD_REMOVE_ME.md b/mflix/server/python-fastapi/README_OLD_REMOVE_ME.md deleted file mode 100644 index 504019a..0000000 --- a/mflix/server/python-fastapi/README_OLD_REMOVE_ME.md +++ /dev/null @@ -1,123 +0,0 @@ -# Welcome to the Python Backend - -TOC -1. [Overview](#overview) -2. [Getting Setup](#getting-setup) -3. [Learning FastAPI](#learning-fastapi) -4. [Exploring the Codebase](#exploring-the-codebase) -5. [Feature Parity Status](#feature-parity-status) -6. [Utilities and Nice to Know](#nice-to-know) - - -## Overview -We're porting our Express backend to Python/FastAPI to achieve **functional parity** - same endpoints, same responses, same MongoDB operations. This allows one frontend to work with multiple backends. - - -**Important**: We're not rewriting - we're replicating behavior exactly. So this means we are figuring out the pythonic way of doing things. You will find that we can accomplish things with Fast in fewer lines of code than in Express. - -## Getting Setup -0. Install Python if you don't already have it. (*Depending on your version of python, you might need to use python3 and pip3 vs python and pip*) -1. Clone from my fork of the main repo. - ```sh - https://github.com/tmcneil-mdb/docs-sample-apps.git - ``` - -2. Checkout my branch - ```sh - git checkout python-backend-setup - ``` - -4. Verify you are on the right branch - ```sh - git branch - ``` -5. In the root directory. /python, make a virtual environment. - ```sh - python -m venv .venv - ``` -6. Activate the virtual environment - ```sh - source .venv/bin/activate - ``` -7. Navigate back to /python, install the required packages. - ```sh - pip install -r requirements.txt - ``` -8. Create an .env file at the /python root. -It should have this format: - ```python - MONGO_URI="place your connection string here" - MONGO_DB="sample_mflix" - ``` -9. Navigate back to the root and start the server. - ```sh - fastapi dev main.py or uvicorn main:app --reload - ``` - (NOTE: THESE WONT WORK IF THE VIRTUAL ENVIRONMENT IS NOT ACTIVATED) -10. Click the link in the terminal or visit ```localhost:8000/docs``` -11. Try visiting ```localhost:8000/api/movies```. - - If the setup ran correctly, you should see data 🎉 - -*I recommend having your atlas instance up to explore your data and query the db directly.* - -**Troubleshooting**: If commands fail, ensure your virtual environment is activated (you should see `(.venv)` in your terminal prompt). - - -## Learning FastAPI -Before diving into the repo, I suggest spending some time with the official [FastAPI tutorial](https://fastapi.tiangolo.com/tutorial/). - -You only need to read up to the 'Request Body' section to get comfortable. *The query parameters and path parameters section can be read later.* - -Key Takeaways: -- Decorators (@app.get, @app.post,etc.) -- Query, path, and body parameters -- Pydantic validation/ serialization -- Automatic JSON responses -- Built-in docs and testing at '/docs' - - -## Exploring the Codebase -Once you have completed the tutorial, I would suggest exploring the code and just noticing the differences between Express and Python. The apps are setup similarly but there are some small differences. - -### Architecture -|Layer|Purpose|Express Equivalent| Differences| -|:---|:-------|:----------|:------| -|Routes
`src/routers/movies.py`| Defines all /movies endpoints (GET, POST, PUT, etc.)| /controllers/movieController.ts |The movies.ts file inside the routes file in the Express backend it actually wiring up the endpoints. Fast handles this for us in the main.py in one line. ```app.include_router(movies.router, prefix="/api/movies", tags=["movies"])```| -|Models
`src/models/models.py`| Pydantic schema for validating and serializing request/response data.| /types/index.ts|There are some differences in how the models are constructed. Take note on how nested classes are handled.| -|Utils
`src/utils/errorHandler.py`| Centralized utilities for responses, error handling and MongoDB exception mapping.|utils/errorHandler.ts |Express requires devs to write exception handling and validation on their own. Pydanic handles the validation and exception handling is a bit cleaner in Fast. You will notice the most differences here.| -|Database
`src/database/mongo_client.py`| Handles the connection to the db|/config/database.ts| *The current database file does not have feature parity with the Express version*| - - -## Feature Parity Status -|Feature|Status|Owner|Notes| -|:------|:-----|:----|:----| -|Global Exception Handling| DONE| - |Found in Utils | -|JSON Response Matching| DONE | - |Found in Utils| -|CRUD- ```insertOne()```| Not Started| Angela| - | -|CRUD- ```insertMany()```| Not Started| Taylor| - | -|CRUD- ```findOne()```| Not Started| Angela| - | -|CRUD- ```find()```| DONE| - | Found in movies.py as ```get_all_movies()``` This is a good function to look at to understand query parameters, requests and responses. Your functions will be simpler than this. But that is a good base to start with.| -|CRUD- ```updateOne()```| Not Started| Angela| - | -|CRUD- ```updateMany()```| Not Started| Taylor| - | -|CRUD- ```deleteOne()```| Not Started| Angela| - | -|CRUD- ```deleteMany()```| Not Started| Taylor| -| -|CRUD- ```findOne()```| Not Started| Angela| - | -|CRUD- ```findOneAndDelete()```| Not Started| Angela| This one is a bit harder but I figure this could be a fun challenge.| - - -## Nice to Know -### Utilities (errorHandler.py) -This module provides a parity replacement for the Express errorHandler.ts file. It provides the same response shapes and error handling and removes the middleware. - -- create_success_response(data,message) - creates a success response with the same shape as the Express version. -- create_error_response(message,code,details) - creates a error response with the same shape as the Express version. -- parse_mongo_exception(exc) - ensures PyMongo exceptions return JSON identical to the Express Version -- register_error_handlers - hooks our error system into the Fast app - -Fast automatically handles async and validation errors, so there is no need for asyncHandler or validateRequiredFields from the TS version. - -### Useful Links -- [Main Repo]( https://github.com/mongodb/docs-sample-apps/tree/main ) -- [Sample App Scoping Doc](https://docs.google.com/document/d/12dROckw_Cp0ku2IIGku-ch7MvEuBPo0V4Gs-5wQgeHQ/edit?tab=t.0) -- [Sample App Project Description & Breakdown Doc](https://docs.google.com/document/d/1xv2dmcNrT-HYk5TBE-KtVDPmW0274rpBZ0_0QmC66ac/edit?tab=t.0#heading=h.ki9tatw08ilc) \ No newline at end of file