How to use the fastapi.responses.JSONResponse function in fastapi

To help you get started, we’ve selected a few fastapi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github augerai / a2ml / a2ml / server / server.py View on Github external
def __render_json_response(data):
    res = {
        'meta': { 'status': 200 },
        'data': data,
    }

    content = jsonable_encoder(res)
    return JSONResponse(content=content)
github deepset-ai / haystack / rest_api / controller / feedback.py View on Github external
def doc_qa_feedback(feedback: Feedback):
    if feedback.answer and feedback.offset_start_in_doc:
        elasticsearch_client.index(index=DB_INDEX_FEEDBACK, body=feedback.dict())
    else:
        return JSONResponse(
            status_code=status.HTTP_400_BAD_REQUEST,
            content="doc-qa feedback must contain 'answer' and 'answer_doc_start' fields.",
        )
github msys2 / msys2-web / app / web.py View on Github external
@router.post("/webhook", response_class=JSONResponse)
async def github_payload(request: Request) -> Response:
    secret = os.environ.get("GITHUB_WEBHOOK_SECRET")
    if not secret:
        raise HTTPException(500, 'webhook secret config incomplete')

    if not await check_github_signature(request, secret):
        raise HTTPException(400, 'Invalid signature')

    event = request.headers.get('X-GitHub-Event', '')
    if event == 'ping':
        return JSONResponse({'msg': 'pong'})
    if event == 'push':
        account = os.environ.get("APPVEYOR_ACCOUNT")
        project = os.environ.get("APPVEYOR_PROJECT")
        token = os.environ.get("APPVEYOR_TOKEN")
        if not account or not project or not token:
github QwantResearch / idunn / idunn / directions / client.py View on Github external
start_lon, start_lat = self.place_to_url_coords(start)
        end_lon, end_lat = self.place_to_url_coords(end)
        response = self.session.get(
            f"{self.QWANT_BASE_URL}/{start_lon},{start_lat};{end_lon},{end_lat}",
            params={
                "type": mode,
                "language": lang,
                **MapboxAPIExtraParams(**extra).dict(exclude_none=True),
            },
            timeout=self.request_timeout,
        )

        if 400 <= response.status_code < 500:
            # Proxy client errors
            return JSONResponse(content=response.json(), status_code=response.status_code)
        response.raise_for_status()
        return DirectionsResponse(**response.json())
github tortoise / tortoise-orm / tortoise / contrib / fastapi / __init__.py View on Github external
async def doesnotexist_exception_handler(request: Request, exc: DoesNotExist):
            return JSONResponse(status_code=404, content={"detail": str(exc)})
github QwantResearch / idunn / idunn / api / places.py View on Github external
lang: str = None,
    type=None,
    verbosity=DEFAULT_VERBOSITY,
):
    """Main handler that returns the requested place"""
    verbosity = validate_verbosity(verbosity)
    lang = validate_lang(lang)
    try:
        place = place_from_id(id, type)
    except InvalidPlaceId as e:
        raise HTTPException(status_code=404, detail=e.message)
    except RedirectToPlaceId as e:
        path_prefix = request.headers.get("x-forwarded-prefix", "").rstrip("/")
        path = request.app.url_path_for("get_place", id=e.target_id)
        query = request.url.query
        return JSONResponse(
            status_code=303,
            headers={"location": str(URL(path=f"{path_prefix}{path}", query=query))},
            content={"id": e.target_id},
        )
    log_place_request(place, request.headers)
    if settings["BLOCK_COVID_ENABLED"] and settings["COVID19_USE_REDIS_DATASET"]:
        background_tasks.add_task(covid19_osm_task)
    return place.load_place(lang, verbosity)
github dapr / python-sdk / ext / dapr-ext-fastapi / dapr / ext / fastapi / actor.py View on Github external
def _wrap_response(
        status_code: int,
        msg: Any,
        error_code: Optional[str] = None,
        content_type: Optional[str] = DEFAULT_CONTENT_TYPE):
    resp = None
    if isinstance(msg, str):
        response_obj = {
            'message': msg,
        }
        if not (status_code >= 200 and status_code < 300) and error_code:
            response_obj['errorCode'] = error_code
        resp = JSONResponse(content=response_obj, status_code=status_code)
    elif isinstance(msg, bytes):
        resp = Response(content=msg, media_type=content_type)
    else:
        resp = JSONResponse(content=msg, status_code=status_code)
    return resp