Sending Data
Firstly, we need to decide how do we send the data in the post request of the API. So we are sending a base64 encoded string representing the image along with the image extension appended to it, for example, data:image/png;base64,iVBORw0KGgoAAAANS. This is a widely used format for showing images over the web. So when we send a POST request we send a json encoded body like:
{
"data": "data:image/png;base64,iVBORw0KGgoAAAANS"
}
Converting Base64 Data to Image
There are 2 parts of the data in the string that we receive. The first part basically tells us the format of the image(.gif in this case) and string encoding(base64 in this case), the second part gives us the encoded string. So, from the first part, we extract the file extension for the image file to be created. We use uuid.uuid4() for a random filename.
filename = '{}.{}'.format(str(uuid.uuid4()).data.split(";")[0].split("/")[1])
file.write(data.split(",")[1].decode("base64")
API Response
Finally using whatever logic you are using for serving your static files, you generate the static file path for the image saved. And then create another json encoded response which returns you the url for the saved image in the server.
{
"url": "https://xyz.storage.com/asd/fgh/hjk/1233456.png"
}