{"id":15142648,"url":"https://github.com/nishanthmuruganantham/dynamic-formula-execution-api","last_synced_at":"2026-01-07T08:04:29.690Z","repository":{"id":257241459,"uuid":"853253378","full_name":"NishanthMuruganantham/dynamic-formula-execution-api","owner":"NishanthMuruganantham","description":"A FastAPI-based API for evaluating dynamic mathematical expressions on datasets. It is developed for a coding Challenge conducted by 'doselect', a collaborative and technology independent hiring tool for companies, for Cognida.ai","archived":false,"fork":false,"pushed_at":"2024-09-14T19:16:59.000Z","size":33,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-29T04:24:28.001Z","etag":null,"topics":["api","api-development","coding-challenge","coding-interview","coding-interview-challenges","data-science","fastapi","fastapi-framework","formula","hackathon","mathematics","pytest","python","python-api","python-project","pythonprograms","swagger-api","topological-sort","vercel","vercel-deployment"],"latest_commit_sha":null,"homepage":"https://dynamic-formula-execution-api.vercel.app","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/NishanthMuruganantham.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-09-06T09:39:08.000Z","updated_at":"2024-09-15T11:02:26.000Z","dependencies_parsed_at":"2024-09-15T13:46:28.577Z","dependency_job_id":"7b469ff7-55cc-4c4c-bca2-94b5b3b08342","html_url":"https://github.com/NishanthMuruganantham/dynamic-formula-execution-api","commit_stats":null,"previous_names":["nishanthmuruganantham/dynamic-formula-execution-api"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NishanthMuruganantham%2Fdynamic-formula-execution-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NishanthMuruganantham%2Fdynamic-formula-execution-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NishanthMuruganantham%2Fdynamic-formula-execution-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NishanthMuruganantham%2Fdynamic-formula-execution-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/NishanthMuruganantham","download_url":"https://codeload.github.com/NishanthMuruganantham/dynamic-formula-execution-api/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246368676,"owners_count":20766062,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-development","coding-challenge","coding-interview","coding-interview-challenges","data-science","fastapi","fastapi-framework","formula","hackathon","mathematics","pytest","python","python-api","python-project","pythonprograms","swagger-api","topological-sort","vercel","vercel-deployment"],"created_at":"2024-09-26T09:43:18.465Z","updated_at":"2026-01-07T08:04:29.683Z","avatar_url":"https://github.com/NishanthMuruganantham.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n# Dynamic Formula Execution API 🚀\n\n## Overview 📝\n\nThe **Dynamic Formula Execution API** is a Python-based API that interprets and executes complex mathematical formulas on structured datasets. It supports formula chaining, validation, and real-time calculation of values across various data types, such as numbers, strings, booleans, dates, and currencies. The solution ensures efficient performance with sub-second response times, making it suitable for large datasets and complex workflows.\n\nThis API was developed as part of a coding challenge to demonstrate key skills in Python and API development.\n\n## Why FastAPI? 🏎️\n\nFastAPI was selected for the following reasons:\n- **⚡ Performance**: FastAPI is one of the fastest Python web frameworks, built on top of ASGI and supports async programming, which helps to efficiently handle I/O-bound operations.\n- **💼 Ease of Use**: FastAPI has automatic request validation, serialization, and generation of OpenAPI documentation, which helps to reduce boilerplate code and improve development speed.\n\n## Requirements 📦\n\n- **Python 3.8+** 🐍\n- **Pydantic**: For data validation. 🛠️\n- **FastAPI**: For building the API. 🚧\n- **Uvicorn**: For serving the application. 🌐\n- **re**: For regex operations in currency/percentage parsing. 💲\n\n## Project Structure 🗂️\n\n```bash\n.\n├── src\n│   ├── app.py              # 💻 it houses the core FastAPI app\n│   ├── logic.py            # 🧬 it houses all the logic associated with the API which involves Formula validation, execution, etc.,\n│   ├── models.py           # 📊 Contains the pydantic models needed such as Data, Formula, Inputs, and ResultBody models\n│   └── routes.py           # 🔗 Contains the route function for the given endpoint /api/execute-formula\n├── tests\n│   └── ErrorTests.py       # ❌ Pytests for validating Exception cases\n│   └── SuccessTests.py     # ✅ Pytests for validating expected success scenarios\n├── .gitignore              # 🙈 specifies files and directories Git should ignore\n├── main.py                 # 🚀 runs the FastAPI app with live reloading using Uvicorn server \n└── pyproject.toml          # 🧩 Project metadata and configuration settings\n├── README.md               # 📄 This file\n├── requirements.txt        # 📜 Dependencies for the project\n├── vercel.json             # ✈️ Contains the vercel deployment configuration\n```\n\n## Setup Instructions 🛠️\n\n### Prerequisites\n\nBefore setting up the project, ensure that the following dependencies are installed:\n\n- Python 3.8+\n- FastAPI\n- Pydantic\n- pytest (for running tests)\n\n### Installation\n\n1. **Clone the Repository**:\n\n    ```bash\n    git clone https://github.com/NishanthMuruganantham/dynamic-formula-execution-api.git\n    cd dynamic-formula-execution-api\n    ```\n\n2. **Create a Virtual Environment**:\n\n    ```bash\n    python3 -m venv venv\n    source venv/bin/activate  # For Windows: venv\\Scripts\\activate\n    ```\n\n3. **Install Dependencies**:\n\n    Use `pip` to install the required dependencies from `requirements.txt`:\n\n    ```bash\n    pip install -r requirements.txt\n    ```\n\n4. **Run Tests**:\n\n    Execute the unit tests to ensure everything is set up correctly:\n\n    ```bash\n    pytest\n    ```\n4. **Run the Server**:\n\n    Running the server locally:\n\n    ```bash\n    python main.py\n    ```\n\n### API Endpoints 🌐\n\nThe API exposes endpoints to execute formulas dynamically using FastAPI. The main endpoint accepts the dataset and the list of formulas to be executed.\n\n#### Endpoint: `/api/execute-formula`\n- **Method**: `POST`\n- **Description**: Executes the provided formulas on the given data and returns the results.\n\n## Usage 📈\n\nTo use the API, you can run the FastAPI server locally:\n\n```bash\npython main.py\n```\n\nThis will start the API, and you can use tools like **Postman** or **cURL** to send requests to the `/execute-formulas` endpoint.\n\n### Example - 1 | Simple Addition \n\n#### Request Payload:\n```json\n{\n    \"data\": [\n        {\n            \"id\": 1,\n            \"fieldA\": 10\n        },\n        {\n            \"id\": 2,\n            \"fieldA\": 20\n        }\n    ],\n    \"formulas\": [\n        {\n            \"outputVar\": \"result\",\n            \"expression\": \"fieldA + 10\",\n            \"inputs\": [\n                {\n                    \"varName\": \"fieldA\",\n                    \"varType\": \"number\"\n                }\n            ]\n        }\n    ]\n}\n```\n\n#### Response:\n```json\n{\n    \"results\": {\n        \"result\": [\n            20,\n            30\n        ]\n    },\n    \"message\": \"The formulas were executed successfully.\",\n    \"status\": \"success\"\n}\n```\n\n### Example - 2 | Formula Chaining\n\n#### Request Payload:\n```json\n{\n    \"data\": [\n        {\n            \"id\": 1,\n            \"fieldA\": 10,\n            \"fieldB\": 2\n        },\n        {\n            \"id\": 2,\n            \"fieldA\": 20,\n            \"fieldB\": 3\n        }\n    ],\n    \"formulas\": [\n        {\n            \"outputVar\": \"sumResult\",\n            \"expression\": \"fieldA + fieldB\",\n            \"inputs\": [\n                {\n                    \"varName\": \"fieldA\",\n                    \"varType\": \"number\"\n                },\n                {\n                    \"varName\": \"fieldB\",\n                    \"varType\": \"number\"\n                }\n            ]\n        },\n        {\n            \"outputVar\": \"finalResult\",\n            \"expression\": \"sumResult * 2 + fieldA\",\n            \"inputs\": [\n                {\n                    \"varName\": \"sumResult\",\n                    \"varType\": \"number\"\n                },\n                {\n                    \"varName\": \"fieldA\",\n                    \"varType\": \"number\"\n                }\n            ]\n        }\n    ]\n}\n```\n\n#### Response Example:\n```json\n{\n    \"results\": {\n        \"sumResult\": [\n            12,\n            23\n        ],\n        \"finalResult\": [\n            34,\n            66\n        ]\n    },\n    \"message\": \"The formulas were executed successfully.\",\n    \"status\": \"success\"\n}\n```\n\n### Example - 3 | Sales Revenue\n\n#### Request Payload:\n```json\n{\n    \"data\": [\n        {\n            \"id\": 1,\n            \"product\": \"Laptop\",\n            \"unitPrice\": \"1000 USD\",\n            \"quantity\": 5,\n            \"discount\": \"10%\"\n        },\n        {\n            \"id\": 2,\n            \"product\": \"Smartphone\",\n            \"unitPrice\": \"500 USD\",\n            \"quantity\": 10,\n            \"discount\": \"5%\"\n        },\n        {\n            \"id\": 3,\n            \"product\": \"Tablet\",\n            \"unitPrice\": \"300 USD\",\n            \"quantity\": 15,\n            \"discount\": \"0%\"\n        }\n    ],\n    \"formulas\": [\n        {\n            \"outputVar\": \"revenue\",\n            \"expression\": \"((unitPrice * quantity) - (unitPrice * quantity * (discount / 100)))\",\n            \"inputs\": [\n                {\n                    \"varName\": \"unitPrice\",\n                    \"varType\": \"currency\"\n                },\n                {\n                    \"varName\": \"quantity\",\n                    \"varType\": \"number\"\n                },\n                {\n                    \"varName\": \"discount\",\n                    \"varType\": \"percentage\"\n                }\n            ]\n        }\n    ]\n}\n```\n\n#### Response Example:\n```json\n{\n    \"results\": {\n        \"revenue\": [\n            4500,\n            4750,\n            4500\n        ]\n    },\n    \"message\": \"The formulas were executed successfully.\",\n    \"status\": \"success\"\n}\n```\n\n## Public Deployment 🌎\n\nThe **Dynamic Formula Execution API** has been **publicly deployed** and can be accessed via **Vercel**.\n\n**Live API URL**: [https://dynamic-formula-execution-api.vercel.app](https://dynamic-formula-execution-api.vercel.app)\n\nThis live deployment allows users to directly interact with the API for formula execution. Access it from Postman to perform POST calls.\n\n## Features  🌟\n\n- **Dynamic Expression Evaluation**: Supports dynamic evaluation of mathematical expressions based on input variables.\n- **Formula Chaining**: Formulas can depend on the output of other formulas, allowing for complex workflows.\n- **Topological Sorting**: Ensures that formulas are executed in the correct order based on their dependencies.\n- **Error Handling**: Provides robust error handling for invalid expressions and missing input variables.\n- **Extensible Framework**: Easily extendable to support additional data types or more complex formula logic.\n\n## Key Components 🔑\n\n### FormulaExecutor Class\n\nThe `FormulaExecutor` class is responsible for processing a list of formulas on the dataset. It first sorts the formulas based on their dependencies using topological sorting and then evaluates each formula dynamically.\n\n#### Key Methods:\n- **`perform_formula_execution`**: Executes all formulas in the correct order and returns the results.\n- **`_perform_topogical_sort_for_formulas`**: Sorts formulas based on dependencies.\n- **`_execute_formula_for_given_data`**: Safely evaluates a single formula on a given dataset.\n\n### Models 📋\n\n- **Data**: Represents the dataset structure.\n- **Formula**: Defines each formula's expression and input-output variables.\n- **Inputs**: Represents input variables for formulas.\n- **ResultBody**: Holds the results of formula executions.\n\n## Links 🔗\n\n1) 🏁 Hackathon Link - https://hackathon-app.doselect.com/1464/problem/1poryb\n2) 💻 Vercel Hosted API domain - https://dynamic-formula-execution-api.vercel.app\n3) 📜 Swagger UI - An interactive documentation interface provided by FastAPI - https://dynamic-formula-execution-api.vercel.app/docs\n4) ReDoc -  Another option for API documentation, offering a different interface. - https://dynamic-formula-execution-api.vercel.app/redoc\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnishanthmuruganantham%2Fdynamic-formula-execution-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnishanthmuruganantham%2Fdynamic-formula-execution-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnishanthmuruganantham%2Fdynamic-formula-execution-api/lists"}