How to authenticate in the Wigle API for get requests - json

I'm trying to query the Wigle API from a jupyter notebook with the code below, but keep receiving the following error:
HTTPError: 401 Client Error: Unauthorized for url: https://api.wigle.net/api/v2/network/search?onlymine=false&freenet=false&paynet=false&ssidlike=Marriott
I suspect it has something to do with authentication, but in the documentation page on Wigle, I don't see/understand where I would include my api key. Any help would be greatly appreciated.
The below code is what I tried:
import requests
import json
ssidlike = "Marriott"
url = f"https://api.wigle.net/api/v2/network/search?onlymine=false&freenet=false&paynet=false&ssidlike={ssidlike}"
response = requests.get(url)
response.raise_for_status()
if response.status_code != 204:
return response.json()
I expected to receive a JSON return of the above query, but what resulted was the following error:
HTTPError: 401 Client Error: Unauthorized for url: https://api.wigle.net/api/v2/network/search?onlymine=false&freenet=false&paynet=false&ssidlike=Marriott

Related

Apps Script - How to solve a truncated output from the console [duplicate]

I'm getting an error response from the API that I'm using, but Google scripts seems to truncate the message. How can I see the full message in Google scripts?
This is the message:
Request failed for https://api.myintervals.com/task/ returned code 400. Truncated server response: {"personid":"180761","status":"Bad Request","code":400,"error":{"code":18,"message":"Validation error has occurred (missing required field/paramet... (use muteHttpExceptions option to examine full response) (line 171, file "IntervalsPull")
Just as #DrSatan1 pointed in the comment, pass muteHttpExceptions option in the parameter to suppress the exception and get the error returned as HTTPResponse.
options = {muteHttpExceptions: true};
var response = UrlFetchApp.fetch("https://api.myintervals.com/task/", options);
Logger.log(response.getContentText());
Now view your logs to see the complete error response.
While setting response to logger or console works, even that will be truncated if the response is too long. You may have to set the response to Drive in such cases.
options.muteHttpExceptions = true;
const res = UrlFetchApp.fetch(url, options);
console.log(res.getResponseCode());
console.log(res);
DriveApp
.getFoldersByName('test'/*A folder in Drive*/)
.next()
.createFile(res.getBlob().setName('response'))

Flask API can receive posts from AJAX but not Postman

We have a Flask API that talks to multiple sources, a web app, and an external source. In the web app, we use AJAX to send a JSON post to the API which is successful. From an external source, whether it's postman or the VaRest Unreal Engine plugin, we get a 400 Error: Bad Request even though we use the correct content-type header.
If anyone can help us figure out why the posts we are sending aren't properly identified we would really appreciate it.
Thanks
This is the JS code from our web app, used to create the JSON which is sent through AJAX (this is the successful code)
var but1 = document.getElementById('but1');
const data1 = {
number: 1 ,
type: 1 ,
value: 100
}
but1.addEventListener("click", function() {
$.post(url, data1);
});
This is a post route in our python API that takes in the input and saves it to a file we have
#app.route('/button', methods=['POST'])
def button():
buttonLog = open("buttonLog.txt", "w")
buttonLog.write(request.form['number'])
buttonLog.close()
typeOf = int(request.form['type'])
value = int(request.form['value'])
return "success"
Here is our JSON post, with headers
Postman JSON
Postman Headers
The AJAX post works as intended, but the postman post/Unreal engine post are not being seen as "posts" to the API.

Want to receive json response for GET request. Postman gives me the json data. But when I do it programatically it returns empty html

import requests
import json
#Infrastructure API URL
url = "http://10.39.188.69/server-manager/tomcat/bimws/rest/v1/infrastructures/?format=json"
myResponse = requests.get(url, headers=headers, verify=False)
print myResponse
print(myResponse.status_code)
#print(myResponse.text)
print(myResponse.json)
Output i get:
c:\automation>python rest_API.py
C:\Python27\lib\site-
packages\requests\packages\urllib3\connectionpool.py:852:
nsecureRequestWarning: Unverified HTTPS request is being made. Adding
certificate verification is strongly advised. See:
https://urllib3.readthedocs.io/en/late/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py:852:
nsecureRequestWarning: Unverified HTTPS request is being made. Adding certifica
e verification is strongly advised. See: https://urllib3.readthedocs.io/en/late
t/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
<Response [200]>
<bound method Response.json of <Response [200]>>
Try doing myResponse.json(). myResponse.json returns an instancemethod type while myResponse.json() will return the json data.

NodeJS request-json setting header breaks

I'm using request-json, found on npm, to query my API server. My server requires that an auth token be passed in the header, but using request-json's method of setting headers produces the following error:
Error: "name" and "value" are required for setHeader().
at ClientRequest.OutgoingMessage.setHeader (_http_outgoing.js:333:11)
at new ClientRequest (_http_client.js:101:14)
at Object.exports.request (http.js:49:10)
at Request.start (C:\Users\Michael\Desktop\FrescoWeb\node_modules\request-js
on\node_modules\request\request.js:904:30)
at Request.write (C:\Users\Michael\Desktop\FrescoWeb\node_modules\request-js
on\node_modules\request\request.js:1625:10)
at end (C:\Users\Michael\Desktop\FrescoWeb\node_modules\request-json\node_mo
dules\request\request.js:666:16)
at Immediate._onImmediate (C:\Users\Michael\Desktop\FrescoWeb\node_modules\r
equest-json\node_modules\request\request.js:690:7)
at processImmediate [as _immediateCallback] (timers.js:358:17)
I'm setting the header and hitting the endpoint in the following code:
var api = requestJson.createClient(config.API_URL);
api.headers['authtoken'] = req.session.token;
api.post(
'/v1/outlet/update',
params,
function(error, response, body){
if (error)
return res.json({err: error}).end();
if (!body)
return res.json({err: 'ERR_MISSING_BODY'}).end();
if (body.err)
return res.json({err: body.err}).end();
req.session.user.outlet = body.data;
req.session.save(function(){
res.json({}).end();
});
}
);
When I comment api.headers['authtoken'] = req.session.token; out, the call doesn't crash. Is there something that I am doing wrong, or do I have to migrate to request for http requests?
req.session.token should be req.session.user.token

How to JSON format an HTTP error response in webapp2

I am using webapp2 for development in App Engine. What I would like to do is to send a custom JSON formatted response in case of an error. For example when the request length is larger that a threshold, to respond with HTTP 400 and response body
{'error':'InvalidMessageLength'}
In webapp2, there is the option to assign error handlers for certain exceptions. For example:
app.error_handlers[400] = handle_error_400
Where handle_error_400 is the following:
def handle_error_400(request, response, exception):
response.write(exception)
response.set_status(400)
When webapp2.RequestHandler.abort(400) is executed, the above code is executed.
How is it possible to have different response formats (HTML and JSON) dynamically based on the above setup? That is, how it is possible to call different versions of handle_error_400 function?
Here is a fully working example that demonstrates how to have the same error handler for all kind of errors and if your URL starts with /json then the response will be an application/json (use your imagination on how you could make a good use of the request object to decide what kind of response you should provide):
import webapp2
import json
def handle_error(request, response, exception):
if request.path.startswith('/json'):
response.headers.add_header('Content-Type', 'application/json')
result = {
'status': 'error',
'status_code': exception.code,
'error_message': exception.explanation,
}
response.write(json.dumps(result))
else:
response.write(exception)
response.set_status(exception.code)
app = webapp2.WSGIApplication()
app.error_handlers[404] = handle_error
app.error_handlers[400] = handle_error
In the above example you can easily test the different behaviours by visting the following URLs that will return a 404 which is the easiest error to test:
http://localhost:8080/404
http://localhost:8080/json/404