This article is a tutorial on how to generate a meme using Python and ImgFlip API.
Snip of the Meme Generated in the article
This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.
pip install requests urllib
Snip of the Sign Up page of ImgFlip
After signing up on ImgFlip, we can use our username and password to communicate with the API. These credentials are required for generating a new meme and not required while fetching the meme templates.
import requests
import urllib
username = 'AjinkyaSonawane'
password = 'dailypy1'
userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 \
Safari/537.36'
Documentation of API for fetching meme template
#Fetch the available memes
data = requests.get('https://api.imgflip.com/get_memes').json()['data']['memes']
images = [{'name':image['name'],'url':image['url'],'id':image['id']} for image in data]
#List all the memes
print('Here is the list of available memes : \n')
ctr = 1
for img in images:
print(ctr,img['name'])
ctr = ctr+1
ctr is a counter used to display as a serial number. It will also be used to fetch the template_id of the selected meme.
Snip of the Output of the above code snippet
Snip of the required parameters for generating the meme
#Take input from user -- Meme, Text0 and Text1
id = int(input('Enter the serial number of the meme : '))
text0 = input('Enter first text : ')
text1 = input('Enter second text : ')
Snip of the Output of the above code snippet
#Fetch the generated meme
URL = 'https://api.imgflip.com/caption_image'
params = {
'username':username,
'password':password,
'template_id':images[id-1]['id'],
'text0':text0,
'text1':text1
}
response = requests.request('POST',URL,params=params).json()
print(response)
Snip of the Output of the above code snippet
#Save the meme
opener = urllib.request.URLopener()
opener.addheader('User-Agent', userAgent)
filename, headers = opener.retrieve(response['data']['url'], images[id-1]['name']+'.jpg')
Snip of the Output of the above code snippet
Generate Memes and share them. I hope this article was helpful. Thank you for reading!
#python #api #programming