UjjwalKGupta commited on
Commit
5a3406a
·
verified ·
1 Parent(s): 5bb5853

json_calculator

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from pydantic import BaseModel
3
+
4
+ # Initialize the FastAPI application
5
+ app = FastAPI(
6
+ title="JSON Calculator API",
7
+ description="A simple REST API to perform addition and multiplication on two numbers and return the result as a JSON object.",
8
+ version="1.0.0",
9
+ )
10
+
11
+ # Define the structure of the incoming request data using Pydantic
12
+ # This ensures that any request to the API has these two float fields
13
+ class CalculationInput(BaseModel):
14
+ number_1: float
15
+ number_2: float
16
+
17
+ @app.get("/")
18
+ def read_root():
19
+ """
20
+ A simple root endpoint to check if the API is running.
21
+ """
22
+ return {"status": "ok", "message": "Welcome to the JSON Calculator API. Send a POST request to /calculate."}
23
+
24
+ @app.post("/calculate")
25
+ def calculate_numbers(data: CalculationInput):
26
+ """
27
+ This endpoint receives two numbers, calculates their sum and product,
28
+ and returns the result in a structured JSON format.
29
+ """
30
+ num1 = data.number_1
31
+ num2 = data.number_2
32
+
33
+ # Perform the calculations
34
+ addition_result = num1 + num2
35
+ multiplication_result = num1 * num2
36
+
37
+ # Create the response dictionary
38
+ results_dict = {
39
+ "calculation_inputs": {
40
+ "number_1": num1,
41
+ "number_2": num2
42
+ },
43
+ "calculation_outputs": {
44
+ "addition": addition_result,
45
+ "multiplication": multiplication_result
46
+ }
47
+ }
48
+
49
+ # FastAPI automatically converts this dictionary to a JSON response
50
+ return results_dict