Skip to content

Example python app with fast api #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .github/dependabot.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
version: 2
updates:
- package-ecosystem: "pip"
directory: /
schedule:
interval: "weekly"
day: wednesday
time: "11:30"
timezone: Asia/Kolkata
# Assignees to set on pull requests
assignees:
- "githubofkrishnadhas"
# prefix specifies a prefix for all commit messages. When you specify a prefix for commit messages,
# GitHub will automatically add a colon between the defined prefix and the commit message provided the
# defined prefix ends with a letter, number, closing parenthesis, or closing bracket.
commit-message:
prefix: "dependabot python package"
# Use reviewers to specify individual reviewers or teams of reviewers for all pull requests raised for a package manager.
reviewers:
- "devwithkrishna/admin"
# Raise pull requests for version updates to pip against the `main` branch
target-branch: "main"
# Labels on pull requests for version updates only
labels:
- "pip"
- "dependencies"
# Increase the version requirements for Composer only when required
versioning-strategy: increase-if-necessary
# Dependabot opens a maximum of five pull requests for version updates. Once there are five open pull requests from Dependabot,
# Dependabot will not open any new requests until some of those open requests are merged or closed.
# Use open-pull-requests-limit to change this limit.
open-pull-requests-limit: 10
33 changes: 33 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: create release on example python application

on:
pull_request:
types:
- closed
branches:
- main
run-name: create release from pr number ${{ github.event.number }}
jobs:
create-release:
runs-on: ubuntu-latest

steps:

- name: Token generator
uses: githubofkrishnadhas/github-access-using-githubapp@v2
id: token-generation
with:
github_app_id: ${{ secrets.TOKEN_GENERATOR_APPID }}
github_app_private_key: ${{ secrets.TOKEN_GENERATOR_PRIVATE_KEY }}

- name: Checkout Repository
uses: actions/checkout@v4
with:
token: ${{ steps.token-generation.outputs.token }}

- name: create-release
uses: devwithkrishna/devwithkrishna-create-release-action@v1.0.1
with:
token: ${{ steps.token-generation.outputs.token }}
pr_number: ${{ github.event.number }}
generate_release_notes: true
26 changes: 26 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Use the official Python image as the base image
FROM python:3.11-slim

# Set the working directory in the container
WORKDIR /app

# Copy the Poetry configuration files to the container
COPY pyproject.toml /app/

# Copy the README.md file to the container
COPY README.md /app/

# Install Poetry
RUN pip install poetry

# Install the application dependencies using Poetry
RUN poetry config virtualenvs.create false && poetry install --no-interaction --no-ansi --no-root

# Copy the application code to the container
COPY app /app/app

# Expose the port that the FastAPI application will run on
EXPOSE 8000

# Command to run the application
CMD ["poetry", "run", "uvicorn", "app.quickapi:app", "--host", "0.0.0.0", "--port", "8000"]
83 changes: 81 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,81 @@
# example-python-application
Sample python application
# Example Python Application

This is a sample Python application built using **FastAPI**. The application allows users to submit their name and favorite color, and provides endpoints to retrieve the submitted data. It also includes logging functionality with JSON formatting.

## Features

- **FastAPI** for building RESTful APIs.
- **Pydantic** for data validation and serialization.
- **Logging** with JSON formatting using `python-json-logger`.
- In-memory storage for demonstration purposes.

## Endpoints

### Root Endpoint
- **GET** `/`
- Returns a welcome message.

### Healthcheck
- **GET** `/healthcheck`
- Verifies if the service is running.

### Submit User Color
- **POST** `/usercolour/`
- Accepts a user's name and favorite color.
- **Request Body**:
```json
{
"name": "John Doe",
"favorite_color": "Blue"
}
```
- **Response**:
```json
{
"name": "John Doe",
"favorite_color": "Blue"
}
```

### Get All User Colors
- **GET** `/allusercolour/`
- Returns all submitted user-color mappings.

## Installation

* Clone the repository:
```bash
git clone https://github.com/githubofkrishnadhas/example-python-application.git
cd example-python-application
```

* Install dependencies using Poetry:

```
poetry install
```

Run the application:

```
poetry run uvicorn app.quickapi:app --reload
```
Access the API documentation at http://127.0.0.1:8000/docs.

## Project Structure
```yaml
example-python-application/
├── app/
│ ├── data_model.py # Defines the Pydantic models
│ ├── logging_config.py # Configures logging for the application
│ ├── quickapi.py # Main FastAPI application
├── README.md # Project documentation
├── pyproject.toml # Poetry configuration
```

## Dependencies
* Python: 3.11+
* FastAPI: For building APIs.
* Uvicorn: ASGI server for running the application.
* Pydantic: Data validation and settings management.
* python-json-logger: JSON formatting for logs.
19 changes: 19 additions & 0 deletions app/data_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
This module defines the data models used in the application.

Classes:
UserColorEntry: A Pydantic model representing a user's name and their favorite color.
"""

from pydantic import BaseModel

class UserColorEntry(BaseModel):
"""
Represents a user's name and their favorite color.

Attributes:
name (str): The name of the user.
favorite_color (str): The user's favorite color.
"""
name: str
favorite_color: str
Empty file removed app/main.py
Empty file.
33 changes: 21 additions & 12 deletions app/quickapi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from fastapi import FastAPI
# from pylogs import get_logger
from logging_config import setup_logging
from app.logging_config import setup_logging
from app.data_model import UserColorEntry

# Setup logging
logger = setup_logging()
Expand All @@ -15,11 +15,13 @@
description="Submit your name and favorite color",
version="1.0.0"
)
# In-memory database (for demonstration purposes)
user_colour = []

@app.get("/")
async def root():
"""Default end point.Serves welcome message for the API"""
logger.info("Root endpoint accessed")
# logger = logging.getLogger("myapp")
logger.info("Root endpoint was accessed!")

return {"message": "Hello World"}
Expand All @@ -32,12 +34,19 @@ async def healthcheck():
logger.info("Healthcheck endpoint accessed")
return {"status": "ok"}

# @app.middleware("http")
# async def log_requests(request: Request, call_next):
# logger = logging.getLogger("myapp")
# logger.info(f"Received request: {request.method} {request.url}")
# response = await call_next(request)
# logger.info(f"Response status: {response.status_code}")
# return response


# Create an user_colour mapping
@app.post("/usercolour/", response_model=UserColorEntry)
async def create_item(item: UserColorEntry):
"""Create an item with a username and users favourite colour and return it."""
user_colour.append(item)
print(user_colour)
logger.info(item)
return item

# List all user_colour mappings
@app.get("/allusercolour/")
async def get_all_user_colour():
"""Get all user_colour mappings."""
logger.info("All user_colour mappings accessed")
logger.info(user_colour)
return user_colour
17 changes: 17 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[tool.poetry]
name = "example-python-application"
version = "0.1.0"
description = "Sample Python Application"
authors = ["githubofkrishnadhas <krishnadhasnk1997@gmail.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.11"
fastapi = {extras = ["standard"], version = "*"}
uvicorn = "*"
python-json-logger = "*"
pydantic = "^2.11.3"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"