question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How can I return a 202 Accepted response for long running REST call?

See original GitHub issue

Hope this is the right place for a question.

I have a REST API post request that does a lot of computation, /crunch. Rather than block the event loop I would like /crunch to return 202 Accepted status code along with a token string. Then the user of the API can call get request /result/{token} to check on the status of the computation. This is outlined nicely here for example.

Is it possible to modify the response status code, for example, similar to this approach in Sanic?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

8reactions
tiangolocommented, Mar 2, 2019

@danieljfarrell here’s a bit of history, now in the docs: https://fastapi.tiangolo.com/history-design-future/

And I quoted you 😁

6reactions
rcox771commented, Jan 8, 2019

@danieljfarrell Its really easy to modify the response code to suit your needs. In the example below, I use /jobs to post new jobs to. This returns a HTTP_201_CREATED on submit. You can then take the id that it generates and call GET /jobs/{id} to check the status, along with its HTTP_202_ACCEPTED code 🎉. Note: I’m using deque’s because they’re thread-safe, but I haven’t thoroughly tested this out and haven’t implemented task switching/moving jobs around to different queues. Hope it helps!

from fastapi import FastAPI
from pydantic import BaseModel
from uuid import uuid4
from collections import deque
from starlette.status import HTTP_201_CREATED, HTTP_202_ACCEPTED
# see https://github.com/encode/starlette/blob/master/starlette/status.py

queues = dict(
    pending=deque(),
    working=deque(),
    finished=deque()
)

def get_job(id: str, queue: str = None, order=['finished', 'working', 'pending']):
    _id = str(id)
    # if queue:
    #    order = [queue]
    for queue in order:
        for job in queues[queue]:
            # print(job['id'])
            if str(job['id']) == _id:
                return job, queue
    return 'not found', None #this will fail horribly


app = FastAPI()

class BaseJob(BaseModel):
    data: bytes = None

class JobStatus(BaseModel):
    status: str
    id: str
    data: bytes = None
    result: int = -1


@app.get("/jobs/{id}", response_model=JobStatus, status_code=HTTP_202_ACCEPTED)
async def read_job(id: str):
    job, status = get_job(id)
    d = dict(
        id=job['id'],
        status=status,
        data=job['data'],
        result=job.get('result', -1)
    )
    return d

@app.post("/jobs/", response_model=JobStatus, status_code=HTTP_201_CREATED)
async def create_job(*, job: BaseJob):
    _job = dict(
        id=str(uuid4()),
        status='pending',
        data=job.data
    )
    queues['pending'].append(_job)
    return _job

Submitting a new job, getting its id image

Getting the status for a job, given its id image

Read more comments on GitHub >

github_iconTop Results From Across the Web

Long running ReST requests and status endpoints - Steve Dunn
Some of it says that the polling endpoint should return 202 Accepted until the resource is ready. One such page is on the...
Read more >
HTTP Status 202 (Accepted) - REST
HTTP Status 202 indicates that the request has been accepted for processing, but the processing has not been completed. This status code is ......
Read more >
REST API Best Practices — Decouple Long-running Tasks ...
Queue up the long-running task requested in a message broker. Respond to the user immediately so they can get back to their busy...
Read more >
When returning a `202` containing a status endpoint, what ...
This page covers the you should return a 202 for long running stuff, but doesn't cover what the status endpoint should return. rest....
Read more >
202 Accepted - HTTP - MDN Web Docs
The HyperText Transfer Protocol (HTTP) 202 Accepted response status code indicates that the request has been accepted for processing, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found