pythonfastapi

How to return a result from a fastapi endpoint processing an array of int32 numbers?


I have to do the following assignment:

Please create a public http or https service. It must have a publicendpoint that accepts array of int32 numbers encoded as json in the request body and returns result as a number. Once deployed, pass the url of that endpoint to this service root in the request body as utf8 encoded string. If successful you will get a success code to give to us via upwork chat.

I have made a service (currently still local) using FastAPI:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class ListRequest(BaseModel):
    numbers: list[int]

@app.post("/")
async def root(request: ListRequest):
    # int32 range
    int32_min = -2**31
    int32_max = 2**31 - 1

    for number in request.numbers:
        if not (int32_min <= number <= int32_max):
            raise HTTPException(status_code=400, detail="All elements must be int32 numbers")
    
    return {"result": "something???"}

I don't understand this part: return result as a number?

Can someone help me what exactly do I need to return?

Thank you.


Solution

  • I Would still recommend asking more question when working on task such as this one.... it is an unclear task and if this is something that would go to production it might lead to multiple problems so don't be shy of asking questions about unclear things.... Also I've gone with the sum result because it's the most "human" go to thing when asked for a "result".

    I am assuming that you cant ask question this is why: I'm assuming what they want from you is to get the sum of the result from the request.number and after that you just need to pass the URL where the numbers will be add together or where the function will return an HTTPException:

    from fastapi import FastAPI, HTTPException
    from pydantic import BaseModel
    from typing import List
    
    app = FastAPI()
    
    class ListRequest(BaseModel):
         numbers: List[int]
    
    
    @app.post("/")
    
    async def root(request: ListRequest):
        # int32 range
    
        int32_min = -2**31
    
        int32_max = 2**31 - 1
    
        for number in request.numbers:
             if not (int32_min <= number <= int32_max):
                 raise HTTPException(status_code=400, detail="All 
                elements must be int32 numbers")
    
    
        result = sum(request.numbers)
    
        return {"result": result}