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.
4
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}
10
I think the task here is to create the interface of such endpoint (schema).
So, to complete this task you need to specify response model and return correct value.
Since it’s not said how you should coerce array to one number, you can use sum
or just return 42
.
Pay attention, that it’s said that you should return result as a number, not as JSON with number.
Also, you can make an improvement of your code by specifying list item’s constraints in your model:
from typing import Annotated, TypeAlias
from annotated_types import Gt, Lt
MyInt: TypeAlias = Annotated[int, Gt(-2**31 - 1), Lt(2**31)]
class InputData(BaseModel):
numbers: list[MyInt]
In this case it will be shown in openapi schema. And you don’t need to check items in your endpoint (FastAPI will do it for you)
7