How can I save the API request in database?

How can I save the API request in database?

I want to send api request once a day when the user refreshes my homepage. So I am saving the result of this request as TEXTFIELD in the database.

But whenever I want to show this list object in the template again. I can’t loop because the result is returning as STRING.

class ShipAPI(models.Model):
    list_saved = models.TextField()
    date_modified = models.DateTimeField(auto_now=True)
    date_published = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.id)

rates = ShipAPI.objects.get(id=5)
type(rates) #string is returning, we need to get this as list.

Frankly, we can convert my question to how should we store the API request in the database.

I’m sorry, I don’t understand what you’re asking for here. It would be helpful if you provided more specific details about exactly what you’re looking for assistance with.

Are you looking to store the request that you are making, or the response that you are receiving from the API?

What api request are you sending? What is coming back?

What do you want to do with it after it returns?

What do you want to “get this as a list”?

When the user logs in to my ship page, I send a request to this URL once a day.

Request Url = “https://api.easyship.com/2022-10/shipments

The data received as a result of this request is as follows:

Response Data = responsedata - cc7ea5d1

I want to save this incoming data in the database and use it during the day without making a request again.

My own method was to save it as TEXTFIELD and save response as a database. But when I pull this data from the database, it returns as STRING. That’s why I’m getting an error while displaying it to the user.

When I pull this data, I need to handle the data as LIST, not STRING.

Sorry, I hope I was able to explain myself.

Thank you.

It appears that what you would be receiving in the response is the string representation of a JSON object.

You might want to save the body of the response as a JSONField. That would prevent you from needing to deserialize this data each time you need to use it.

1 Like

Thank you for your answer.

Right now I’m getting an error like this when doing migrate.
SQLite does not support JSONFields.

When I researched the reason, there was such an error in the python 3.8 version. But I installed my server on amazon elastic beanstalk and it does not support python 3.9

Do you have a solution suggestion?

You have at least three choices:

1 Like

Thank you so much,

Now I found a workaround without upgrading python 3.9.
I did the sqlite3 update and migrate worked.

JSONFields works fine. :innocent: