Joan Rotich, Joe Wanjema and Edwin Mwaniki
A FastAPI-based backend system for the GreenFund platform, designed to help farmers track and manage their environmental impact, get climate-smart agriculture recommendations, and participate in a community-driven knowledge sharing platform.
-
User Management
- Authentication with JWT tokens
- User registration and profile management
- Password hashing with bcrypt
- Email validation
-
Farm Management
- Create and manage farm profiles
- Track farm activities
- Record location and size information
- Monitor current crops
-
Environmental Monitoring
- Climate impact tracking
- Soil health monitoring
- Carbon footprint calculation
- Environmental activity logging
-
Community Features
- Forum discussions
- Achievement badges
- Notifications system
- Knowledge sharing
-
Climate Smart Agriculture
- Climate action recommendations
- Pest and disease alerts
- Water management advice
- Crop suggestions based on soil conditions
- Framework: FastAPI
- Database: PostgreSQL with SQLModel ORM
- Authentication: JWT tokens with bcrypt password hashing
- Container: Docker and Docker Compose
- Migration: Alembic
- Testing: pytest
- API Documentation: Swagger UI (built-in with FastAPI)
This project integrates AI to provide agronomic assistance and enrich soil/farm insights. The AI components combine simple rule-based logic (in app/climate_rules.py) with OpenAI-powered prompts (via app/soil_model.py and app/recommendations.py) to produce actionable guidance.
Key AI-powered capabilities:
- Chatbot: a farmer-facing assistant available at POST
/api/chatbot/ask(router prefix/chatbot). The chatbot uses a system prompt tuned for Kenyan smallholder farmers and returns a short reply. - Soil analysis (text): POST
/api/soil/manualβ submit soil measurements and the system will call the AI to returnai_analysis_textandsuggested_cropswhich are stored with theSoilReport. - Soil analysis (image): POST
/api/soil/upload_soil_image/{farm_id}β upload a soil image; the backend sends the image to the AI multi-modal endpoint and stores the parsed analysis as aSoilReport. - Crop suggestions summary: GET
/api/soil/suggestions/summaryβ aggregates the latest AI suggestions across the user's farms. - Climate actions: endpoints under
/api/climate-actionsuse both rule-based assessments and AI refinement to provide:- Pest/disease alerts: GET
/api/climate-actions/alerts/{farm_id} - Carbon guidance: GET
/api/climate-actions/carbon-guidance/{farm_id} - Water management advice: GET
/api/climate-actions/water-management/{farm_id}
- Pest/disease alerts: GET
Configuration & environment variables:
OPENAI_API_KEYβ required to use OpenAI services. Add it to your.envwhen running with real AI calls.
Example .env snippet:
OPENAI_API_KEY=sk-xxxx-your-key-xxxx
DATABASE_URL=postgresql://postgres:postgres@db:5432/app_db
SECRET_KEY=your_secret_key_hereCost, latency and safety notes:
- AI calls incur costs and add latency to endpoints β consider async patterns, caching, or background tasks for heavier jobs (e.g., large image analysis).
- Limit model usage and add rate-limiting / quotas to protect against abuse and runaway costs (not implemented by default).
- Ensure user consent for sending images/data to third-party AI services and consider redacting sensitive information.
Testing & local development (mocking AI):
- For tests, avoid calling the real OpenAI API. Mock
app.soil_model.get_openai_clientor patch the OpenAI client methods to return canned responses. Example strategies:- Use pytest monkeypatch to replace
get_openai_clientwith a fake client that implements.chat.completions.create. - Use VCR-like fixtures to replay recorded responses if you have stable outputs.
- Use pytest monkeypatch to replace
Security and data retention:
- Store only the AI outputs that are necessary (the app stores
ai_analysis_textandsuggested_crops). Log minimal information about API responses. - Rotate
OPENAI_API_KEYregularly and do not commit it to source control. Use environment-backed secrets (Docker secrets, vault, etc.) in production.
| Farmer's Dashboard | Farms (Card & Map View of Farmer's farms) |
|---|---|
![]() |
![]() |
| Farm Details | Farm - Soil Analysis |
|---|---|
![]() |
![]() |
- Docker and Docker Compose
- Python 3.8+
- PostgreSQL (if running locally)
-
Clone the repository:
git clone https://github.com/Jwanjema/GreenFund-test-Backend.git cd GreenFund-test-Backend -
Create a .env file:
DATABASE_URL=postgresql://postgres:postgres@db:5432/app_db SECRET_KEY=your_secret_key_here ALGORITHM=HS256 ACCESS_TOKEN_EXPIRE_MINUTES=60
-
Start the services using Docker Compose:
docker-compose up --build
-
Create a virtual environment:
python -m venv venv source venv/bin/activate # On Windows use: venv\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
-
Run migrations:
alembic upgrade head
-
Start the development server:
uvicorn app.main:app --reload
-
Interactive Docs (Swagger UI):
π https://greenfund-backend.onrender.com/docs -
Readable Docs (ReDoc):
π https://greenfund-backend.onrender.com/redoc
Use the Swagger version to test endpoints directly.
Use ReDoc for a clean reference overview.
-
Authentication
- POST
/api/auth/register- Register new user - POST
/api/auth/token- Login and get access token
- POST
-
Users
- GET
/api/users/me- Get current user profile - PUT
/api/users/me- Update user profile - POST
/api/users/me/change-password- Change password
- GET
-
Farms
- GET
/api/farms- List user's farms - POST
/api/farms- Create new farm - GET
/api/farms/{farm_id}- Get farm details - PUT
/api/farms/{farm_id}- Update farm details
- GET
-
Environmental Monitoring
- POST
/api/activities- Log farm activity - GET
/api/climate/actions- Get climate action recommendations - POST
/api/soil/reports- Submit soil analysis - GET
/api/soil/reports/{farm_id}- Get soil reports
- POST
-
Community
- GET
/api/forum/threads- List forum threads - POST
/api/forum/threads- Create new thread - GET
/api/badges- List available badges - GET
/api/notifications- Get user notifications
- GET
Run the test suite:
DATABASE_URL=sqlite:/// pytest tests/ -vCreate a new migration:
alembic revision --autogenerate -m "description of changes"Apply migrations:
alembic upgrade head- Secure password hashing using bcrypt
- JWT token authentication
- CORS middleware configuration
- Input validation using Pydantic models
- SQL injection prevention through SQLModel
- Rate limiting on sensitive endpoints
- Fork the repository
- Create your feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
For support, please create an issue in the GitHub repository or contact the development team.




