31

I have HTTP server on aiohttp with . How can I return web.Response() through JSON (from a dict)?

async def api_server(request):
    res = {"q": "qqq", "a": "aaa"}
    return web.Response(res) # <-- as JSON
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
morfair
  • 518
  • 1
  • 6
  • 17

1 Answers1

47

You can use web.json_response:

async def api_server(request):
    res = {"q": "qqq", "a": "aaa"}
    return web.json_response(res)

Furthermore the json_response has additional parameters, like:

json_response(data, text=None, body=None, status=200, reason=None,
              headers=None, content_type='application/json', dumps=json.dumps)

Most of the parameters are the same as the generic web.Response(..), but the dumps is more interesting: it is a reference to a method that converts data into its JSON equivalent. By default it uses json.dumps. If you however plan to write complex objects to the client, you perhaps should alter that. For now it is fine however.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • how can I add a header "Total" here? `match_count = len(matches) headers = {'total': match_count} return web.json_response({"matches": fdata})` – binrebin Apr 20 '20 at 08:47
  • @binrebin: you can pass a dictionary to the `headers` parameter, so something like `web.json_response(res, headers={'Total': '1425'})` – Willem Van Onsem Apr 20 '20 at 08:52