Instagram Invalid Response Error - 400 - django

I have the following code.
params = {'client_id':settings.SOCIAL_AUTH_INSTAGRAM_KEY,
'client_secret':settings.SOCIAL_AUTH_INSTAGRAM_SECRET,
'aspect':'media',
'object':'tag',
'object_id':instance.hashtag,
'callback_url':
'http://subdomain.domain.net:8000/campaigns/hook'}
response = requests.post('https://api.instagram.com/v1/subscriptions',
data=params)
And I get response
'{"meta":{"error_type":"APISubscriptionError","code":400,"error_message":"Invalid
response"}}'
My domain is reachable from outside. Any ideas?

This was because Instagram sends a GET request to my callback_url
and wants me to response with hub.challenge parameter like below
if self.request.GET:
response = request.GET.get('hub.challenge')
return HttpResponse(response)

Related

How to make API call in Flask?

I am trying to make request to Clash of Clan Api and after requesting the right data it returns 200 ok & if i search wrong data it returns 404 not found. How to flash message after the data is not found according to the HTTP response from the API?
my views in flask
#app.route('/player', methods=['GET', 'POST'])
def player():
headers = header
url = ('https://api.clashofclans.com/v1/players/{}')
query = request.form.get('search')
player_id = urllib.parse.quote(query)
stats = requests.get(url.format(player_id), headers=headers).json()
return render_template('player.html', stats=stats, data=stats['achievements'])
stats = requests.get(url.format(player_id), headers=headers).json()
Here, you just take the JSON from the body and discard a bunch of useful data. Instead,
response = requests.get(url.format(player_id), headers=headers)
stats = response.json()
status_code = response.status_code
success = response.ok
# ...
You can see all the things you can get from the Response object in API documentation.

getting code 400 message Bad request syntax , after post from flutter

getting code 400 message Bad request syntax , after post from flutter,
with postman request send and no problem but with flutter after Post Map data to Django server i get this error
[19/May/2020 14:58:13] "POST /account/login/ HTTP/1.1" 406 42
[19/May/2020 14:58:13] code 400, message Bad request syntax ('32')
[19/May/2020 14:58:13] "32" 400 -
Django
#api_view(['POST'])
def login_user(request):
print(request.data)
if request.method == 'POST':
response = request.data
username = response.get('username')
password = response.get('password')
if password is not None and username is not None:
user = authenticate(username=username, password=password)
if user is not None:
create_or_update_token = Token.objects.update_or_create(user=user)
user_token = Token.objects.get(user=user)
return Response({'type': True, 'token': user_token.key, 'username': user.username},
status=status.HTTP_200_OK)
else:
return Response({'type': False, 'message': 'User Or Password Incorrect'},
status=status.HTTP_404_NOT_FOUND)
else:
return Response({'type': False, 'message': 'wrong parameter'}, status=status.HTTP_406_NOT_ACCEPTABLE)
else:
return Response({'type': False, 'message': 'method is wrong'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
flutter
Future<dynamic> postGoa(String endpoint, Map data)async{
Map map = {
"username":"user",
"password":"password"
};
var url = _getUrl("POST", endpoint);
var client = new HttpClient();
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.headers.set('Authorization', 'Bearer '+ athenticated
);
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String mydata= await response.transform(utf8.decoder).join();
client.close();
return mydata;
}
}
after add
request.add(utf8.encode(json.encode(map)));
i get error in Django console
Try printing out your request headers from the Django application.
print(request.headers)
I bet one of the headers is Content-Type: ''. If that is the case, Django isn't reading your POST data because it thinks there is no data. I recommend calculating the length of the content you are sending in Flutter, then sending the correct Content-Length header with your request.
That might look something like this (in your Flutter app):
encodedData = jsonEncode(data); // jsonEncode is part of the dart:convert package
request.headers.add(HttpHeaders.contentLengthHeader, encodedData.length);

KeyError: access token

I have already test this before and it's work. Now the error back again and I didn't do any changes on my social app.
Here are my codes:
def get_profile(request, token=None):
args = {
'client_id': settings.FACEBOOK_APP_ID,
'client_secret': settings.FACEBOOK_APP_SECRET,
'redirect_uri': request.build_absolute_uri(reverse('social:fb_callback')),
'code': token,
}
target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read()
response = cgi.parse_qs(target)
access_token = response['access_token'][-1]
return access_token
Obviously, your request is not successful and the response doesn't have an access token. According to facebook docs, when a request isn't good, it returns a response with an error element, something like:
{
error: {
message: "Missing redirect_uri parameter.",
type: "OAuthException",
code: 191
}
}
So, in your function, you should do something like:
class FacebookAccessException(Exception): pass
def get_profile(request, token=None):
...
response = json.loads(urllib_response)
if 'error' in response:
raise FacebookAccessException(response['error']['message'])
access_token = response['access_token'][-1]
return access_token
PS:
Try to use better urllib. You should try Requests.

Problems passing access token to authenticate with API

I'm trying to get information from the Gimmebar API (redirects to the access token step) and having problems with the last step exchanging the access token for the data.
#getting access token successfully before this
post_url = '/tags'
headers = {'Authorization': 'Bearer %s' % access_token}
query = '/collections'
full_url = '%s%s%s' % (base_url, post_url, query)
req = urllib2.Request(full_url, headers=headers)
response = urllib2.urlopen(req)
the_page = response.read()
It breaks at the urllib2.Request and I'm getting an error that I'm not sure what to do with:
No exception supplied
Exception
Location: /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py
in http_error_default, line 510
Here is the view so you can see how I got to step5...

OAuth authentication failed on PUT

I am using OAuth within my project. but I have come into an authentication problem.
It is that I can pass the authentification mechanism of Oauth with the method "POST" but not the method "PUT". The only difference between the POST and PUT request is the method type. The body and the header is the same. The requests I used are as follows :
POST
resp, cont = client.request("http://localhost:8000/api/1.0/booking/",
"POST",
data_booking,
headers=headers)
PUT
resp, cont = client.request("http://localhost:8000/api/1.0/booking/",
"PUT",
data_booking,
headers=headers)
The client is a OAuth client.
The error message returned by server is :
Fyi : 401 Unauthorized
Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided
I am developing using the django framework.
The request method is as follow :
def request(self, uri, method="GET", body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None,
callback_url=None, realm=''):
DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded'
if not isinstance(headers, dict):
headers = {}
is_multipart = method == 'POST' and headers.get('Content-Type',
DEFAULT_CONTENT_TYPE) != DEFAULT_CONTENT_TYPE
if body and (method == "POST" or method == 'PUT') and not is_multipart:
parameters = dict(parse_qsl(body))
if callback_url != None:
parameters['oauth_callback'] = callback_url
else:
if callback_url != None and not is_multipart:
parameters = {'oauth_callback': callback_url}
else:
parameters = None
req = Request.from_consumer_and_token(self.consumer,
token=self.token, http_method=method, http_url=uri,
parameters=parameters)
req.sign_request(self.method, self.consumer, self.token)
if method == "POST" or method == "PUT":
headers['Content-Type'] = headers.get('Content-Type',
DEFAULT_CONTENT_TYPE)
if is_multipart:
headers.update(req.to_header(realm))
else:
body = req.to_postdata()
elif method == "GET":
uri = req.to_url()
else:
headers.update(req.to_header(realm))
return httplib2.Http.request(self, uri, method=method, body=body,
headers=headers, redirections=redirections,
connection_type=connection_type)
Anyone has an idea?
Some OAuth server implementations only include form-encoded body parameters in the signature base string when the HTTP method is POST. This was the right behavior in OAuth 1.0 but was corrected in later revisions. Try making a PUT request without a body and see if that helps. If it does, you will need to ask the server library maintainer to fix this or limit your calls not to include a form-encoded body when using a put.