How to build a emi calculator api using FastAPI
Tags: fastapi, webdev, tutorial, python
Published: 2023-06-24 10:16:24

## Introduction to FastAPI EMI Calculator API

In this tutorial, you will learn how to create a API using FastAPI to calculate EMI (Equated Monthly Installment) for loans and perform other related financial calculations. FastAPI is a modern, fast, and easy-to-use Python framework for building APIs with automatic documentation generation.

## What is EMI?

EMI stands for Equated Monthly Installment, which is a fixed amount of money that borrowers need to pay to the lender each month as a repayment for a loan. EMI consists of both principal and interest components and is calculated based on the loan amount, interest rate, and tenure.

## Project Setup

To get started, we will use `pyenv` and `poetry` for managing our Python environment and project dependencies. If you haven't installed them yet, follow the prerequisites section in this tutorial to set them up.

Once you have `pyenv` and `poetry` installed, create a new project directory and initialize a new `poetry` project. Install the necessary dependencies, including `fastapi` and `numpy-financial`, which we will use for financial calculations.

## Creating the API Endpoints

With the project set up, we will then define the API endpoints using FastAPI. We will create endpoints to calculate EMI, tenure, principal, and interest rate based on the provided inputs.

- The `/calculate-emi` endpoint will take the loan principal amount, tenure, and interest rate as input and return the calculated EMI.
- The `/calculate-tenure` endpoint will take the loan principal amount, EMI, and interest rate as input and return the tenure.
- The `/calculate-principal` endpoint will take the loan tenure, EMI, and interest rate as input and return the principal amount.
- The `/calculate-rate` endpoint will take the loan principal amount, tenure, and EMI as input and return the interest rate.

## Step 1: Prerequisites

Before starting the project setup, make sure you have the following prerequisites installed on your system:

1. `pyenv`: A Python version management tool. It allows you to easily switch between different Python versions. You can install `pyenv` by following the instructions in the official documentation: [pyenv Installation](https://github.com/pyenv/pyenv#installation)

2. `poetry`: A dependency management and packaging tool for Python. It simplifies the process of managing project dependencies and creating virtual environments. You can install `poetry` by following the instructions in the official documentation: [poetry Installation](https://python-poetry.org/docs/#installation)

## Step 2: Set up the Project

1. Create a new directory for your project and navigate to it in your terminal.

2. Set up the Python version using `pyenv`. This step is optional but recommended to ensure consistency across different environments. Run the following command in your project directory:

   ```bash
   poetry config virtualenvs.in-project true
   pyenv install 3.11.4
   pyenv shell 3.11.4
   ```

3. Initialize a new `poetry` project. Run the following command and follow the prompts:

   ```bash
   poetry init
   poetry env use python
   ```

4. Install the necessary dependencies:

   ```bash
   poetry add fastapi uvicorn numpy-financial
   ```

5. Create a new Python file, such as `main.py`, and open it in a text editor.

## Step 3: Import Dependencies and Set Up FastAPI

In the `main.py` file, import the necessary dependencies and set up the FastAPI application:

```python
from fastapi import FastAPI
import numpy_financial as npf

app = FastAPI()
```

## Step 4: Create the API Endpoints

Define the API endpoints that will handle the financial calculations:

```python
@app.get("/calculate-emi")
def get_emi(principal: float = 100000, tenure: int = 6, rate_of_interest: float = 12):
    emi = npf.pmt(rate_of_interest / 100 / 12, tenure, -principal, when="end")
    return {"emi": round(emi, 2)}


@app.get("/calculate-tenure")
def get_tenure(
    principal: float = 100000, emi: float = 17200, rate_of_interest: float = 12
):
    tenure = npf.nper(rate_of_interest / 100 / 12, -emi, principal, when="end")
    return {"tenure": round(tenure)}


@app.get("/calculate-principal")
def get_principal(tenure: int = 6, emi: float = 17200, rate_of_interest: float = 12):
    principal = npf.pv(rate_of_interest / 100 / 12, tenure, -emi, when="end")
    return {"principal": round(principal, 2)}


@app.get("/calculate-rate")
def get_rate(principal: float = 100000, tenure: int = 6, emi: float = 17200):
    rate = npf.rate(tenure, -emi, principal, 0, when="end") * 12 * 100
    return {"rate_of_interest": round(rate, 2)}
```

## Step 5: Run the Application

Save the `main.py` file and run the FastAPI application using `poetry`:

```bash
poetry run uvicorn main:app --reload
```

You should see output similar to the following:

```bash
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```

Step 6:

## Test the API Endpoints

You can now test the API endpoints in a web browser using the swagger ui visit [http://localhost:8000/docs](http://localhost:8000/docs).

You will get the following UI:

![Swagger UI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/71iwg0er287abxjpz7xe.png)
You can test the EMI calculation by clicking [try it out](http://localhost:8000/docs#/default/get_emi_calculate_emi_get)

![EMI Calculator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t48a6zp31jpk9jk2cc4b.png)
Similarly you can try out all the other end points.

You have successfully created a FastAPI backend that can calculate EMI, tenure, principal, and rate of interest based on the provided inputs using the `numpy_financial` library. Feel free to customize the API endpoints or add additional functionality as needed to learn further.