Send X-Api-Key with Post Request Header Python
I Was Given a Problem That Stated: #Write a Script That Uses a Web Api to Create a Social Media Post. #There Is a Tweet Bot Api Listening at Get / Returns...
I was given a problem that stated:
#Write a script that uses a web API to create a social media post.
#There is a tweet bot API listening at GET / returns basic info about the API.
#POST / with x-api-key:tweetbotkeyv1 and data with user tweetbotuser and a status-update of alientest.
My code responds that I did not provide the x-api-key, but it is in the header. My code:
#
# Tweet bot API listening at
# GET / returns basic info about api. POST / with x-api-key:tweetbotkeyv1
# and data with user tweetbotuser and status-update of alientest
#
import urllib.parse
import urllib.request
data = urllib.parse.urlencode({
"x-api-key": "tweetbotkeyv1",
"connection": "keep-alive",
"User-agent": "tweetbotuser",
"status-update": "alientest"
})
url = ""
data = data.encode("ascii")
with urllib.request.urlopen(url, data) as f:
print(f.read().decode("utf-8"))
returns:
{"success": "false", "message":"x-api-key Not provided", "flag":""}
Is there something wrong with the header?
1 Answer
The url, parameters and header must be submitted in strict order:
urllib.request.Request(url, post_param, header)
the result will be: {"success": "true", "message":"Well done", "flag":"<the flag will be show here>"}
Here is the working solution
import urllib.parse
import urllib.request
url = ""
header={"x-api-key" : 'tweetbotkeyv1'}
post_param = urllib.parse.urlencode({
'user' : 'tweetbotuser',
'status-update' : 'alientest'
}).encode('UTF-8')
req = urllib.request.Request(url, post_param, header)
response = urllib.request.urlopen(req)
print(response.read())