2

I have installed the 'us' module (https://pypi.python.org/pypi/us) to get the US states. It prints the state list. I want to show this in an API in the following format.

{
    "states": [
        {
            "state_code":"CA",
            "state_name":"California"
        },
        {
            "state_code":"AL",
            "state_name":"Alabama"
        }
    ]
}

Now showing the following error.

TypeError at /api/v1/us/states
<State:Alabama> is not JSON serializable

views.py

@api_view(['GET'])
def get_all_states(request):
    states = us.states.STATES
    print (states)
    return Response({'states':states})

When I print the states, It has the following format.

[<State:Alabama>, <State:Alaska>, <State:Arizona>, <State:Arkansas>, <State:California>, <State:Colorado>, <State:Connecticut>, <State:Delaware>  <State:West Virginia>, <State:Wisconsin>, <State:Wyoming>]

urls.py

urlpatterns = [
    url(r'^us/states', get_all_states),
]

I am not using any serializer for this. Is there anyway to iterate over the states and get the formatted states data?

1 Answer 1

6

When you return a dict in Response, django considers and returns it as application/json content-typed response. It uses json library to serialize it. A dict is serializable but a State object is not. You need to inflate it yourself. Something like this.

@api_view(['GET'])
def get_all_states(request):
    states = [{'state_code': x.abbr, 'state_name': x.name} for x in us.states.STATES]
    print (states)
    return Response({'states': states})

As all you need is sort of static data, its always a good idea to cache it. Or inflate it once so that its not repeated on every request.

US_STATES = [{'state_code': x.abbr, 'state_name': x.name} for x in us.states.STATES]

@api_view(['GET'])
def get_all_states(request):
    return Response({'states': US_STATES})

Happy Coding.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.