1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Check if request.json() is NoneType

Discussão em 'Python' iniciado por Stack, Novembro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am making API Calls and expect to get some null responses or NoneTypes. However I am trying to handle them gracefully.

    This is the default behavior:


    res = req.json()
    res.get("key", {}).get("key")

    AttributeError: 'NoneType' object has no attribute 'get'


    Below are the ways I've tried to catch it, but didn't work:

    if res is None or isinstance(res, type(None)) or len(res) == 0


    The NoneType errors in question have len(req.text) = 16 ?
    Vs +1k for the not NoneType errors.

    Currently catching them this way:

    if len(req.text) < 100: # Empty JSON Object
    return None


    But I am pretty sure this isn't the best practice.
    Can someone help resolve this issue ?

    UPDATE


    print(type(res))
    <class 'dict'>

    print(res)
    {'key': None}


    SOLUTION

    if res.get("key") is None:
    return None


    Should have inspected further.

    MEA CULPA

    I am realizing that the AttributeError was about the second .get("key") and not the former .get("key", {}) while I didn't include it (the 2nd get) in my original, unedited, post.

    The type of res.get("key", {}) is None

    Sorry & Thanks to all !

    Continue reading...

Compartilhe esta Página