Gagan Singh
Gagan Singh

Reputation: 230

How to send images in django api?

I'm trying to send my image from django server to app.There are two appoaches for above problem: 1)send url of the image 2)send encoded image I'm not sure which one to use due to following:-

  1. If i choose the first way. Json resoponse will be quicker but if a user returns a page twice, it will make two request on server. Moreever it would be impossible to cache the image.
  2. In case of second approach, i can cache the image at client app, but does encoding increase overall response time from the server?

Which is the recommended approach for sending image from api. Currently i'm sending image by following:-

return JsonResponse({'image':model.image.url})

Upvotes: 0

Views: 2411

Answers (2)

Tim Specht
Tim Specht

Reputation: 3218

You probably want to go with #1 and send over the URL. Usually you would not deliver the image files directly from your server but from a cloud storage like S3 or GCS. More advanced setups even include CDNs (Content Delivery Networks) like Fastly or Cloudfront to enable easy caching and serve traffic on a global scale.

If you should choose to send over the encoded image (in base64 for example), be aware that the increased response size of the body will increase the response times incredibly high and might even lead to complete timeouts at around 30s. Users will ultimately have longer response times, are more likely to churn and you are paying way more for your servers.

Upvotes: 1

bryan60
bryan60

Reputation: 29305

The answer is approach 1. Encoding images will destroy your server response time unless they’re very tiny like thumbnails or avatars, even then I wouldn’t make a habit of it. I’ve seen apps rendered unusable by this practice. Most browsers cache images during sessions automatically. If server performance is a big concern and images are dragging it down, Generally I’ll store images in some kind of static file host though like s3 and use an edge cache anyway in real world environments.

Upvotes: 1

Related Questions