Unable to get data from json server - json-server

I added a object called users in json server.,which can be accessed using http://localhost:3000/users.But when I try to log the data using Http in angular,I get error in console.
Can anyone help?
edit: I checked with jsonapi.typicode.com and that works
Following is the error:
Object { _body: error, status: 0, ok: false, statusText: "", headers: {…}, type: 3, url: null }
core.js:1673
defaultErrorLogger
core.js:1673
./node_modules/#angular/core/fesm5/core.js/ErrorHandler.prototype.handleError
core.js:1719
next
core.js:4319:109
./node_modules/#angular/core/fesm5/core.js/EventEmitter.prototype.subscribe/schedulerFn<
core.js:3555:34
./node_modules/rxjs/_esm5/internal/Subscriber.js/SafeSubscriber.prototype.__tryOrUnsub
Subscriber.js:195
./node_modules/rxjs/_esm5/internal/Subscriber.js/SafeSubscriber.prototype.next
Subscriber.js:133
./node_modules/rxjs/_esm5/internal/Subscriber.js/Subscriber.prototype._next
Subscriber.js:77
./node_modules/rxjs/_esm5/internal/Subscriber.js/Subscriber.prototype.next
Subscriber.js:54
./node_modules/rxjs/_esm5/internal/Subject.js/Subject.prototype.next
Subject.js:47
./node_modules/#angular/core/fesm5/core.js/EventEmitter.prototype.emit
core.js:3539:52
onHandleError/<
core.js:3846:48
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.invoke
zone.js:388
./node_modules/zone.js/dist/zone.js/</Zone.prototype.run
zone.js:138
./node_modules/#angular/core/fesm5/core.js/NgZone.prototype.runOutsideAngular
core.js:3783
onHandleError
core.js:3846
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.handleError
zone.js:392
./node_modules/zone.js/dist/zone.js/</Zone.prototype.runTask
zone.js:191
./node_modules/zone.js/dist/zone.js/</ZoneTask.invokeTask
zone.js:496
ZoneTask/this.invoke
zone.js:485
timer

Related

Uber Eats API - Fail to collect reports (Could not parse json: readObjectStart: expect { or n, but..)

We are facing an error when we are trying to request UberEats API to collect report about our restaurants based on the Ubereats documentation here.
The error :
'{"error":"Could not parse json: readObjectStart: expect { or n, but found \x00, error found in #0 byte of ...||..., bigger context ...||..."}'
We tried to run the query in python and postman and still facing the same error.
Need help to understand where we failed.
Here the python code run in VSC
import requests
import json
payload = {
"report_type": "FINANCE_SUMMARY_REPORT",
"store_uuids": "xxx",
"start_date": "2022-09-01",
"end_date": "2022-09-15"
}
headers = {
"authorization": "Bearer xxx"
}
report_response = requests.post('https://api.uber.com/v1/eats/report', data=payload, headers=headers)
report_response.text
'{"error":"Could not parse json: readObjectStart: expect { or n, but found \x00, error found in #0 byte of ...||..., bigger context ...||..."}'
Best regards,
You have to convert the payload to valid JSON string and send the request.
headers = {
"Authorization" : "*********",
"Content-Type" : "application/json"
}
import json
response = requests.post("https://api.uber.co/v1/eats/report", data = json.dumps(payload), headers=headers)

for a grpc client `listen` function to the stream not working same as `await for (...)`

I have a golang server which streams data and a dart client. I put the following code which seems to be working fine
var response = stub.streamMusic(RequestMusicId(musicId: musicId));
await for(var v in response) {
print(v);
}
but when i tried to listen to the stream using this
var response = stub.streamMusic(RequestMusicId(musicId: musicId));
response.listen((value) {
print(value);
});
i get the following error, even though the server is running.
Connecting to VM Service at http://127.0.0.1:55936/l3_uHzU_qIw=/
Unhandled exception:
gRPC Error (code: 14, codeName: UNAVAILABLE, message: Error connecting: Connection shutting down., details: null, rawResponse: null, trailers: {})
Exited (255)

Error in saving data to mongodb database using flask

I am using a mongodb database with my app in Flask, and I am connecting it to the app with pymongo.
I am having an issue while trying to save documents in my mongodb database, see the error below :
127.0.0.1 - - [01/Oct/2019 15:56:47] "POST /movie HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/lancelot/.local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1385, in _retry_with_session
return func(session, sock_info, retryable)
File "/home/lancelot/.local/lib/python3.6/site-packages/pymongo/collection.py", line 595, in _insert_command
retryable_write=retryable_write)
File "/home/lancelot/.local/lib/python3.6/site-packages/pymongo/pool.py", line 613, in command
user_fields=user_fields)
File "/home/lancelot/.local/lib/python3.6/site-packages/pymongo/network.py", line 167, in command
parse_write_concern_error=parse_write_concern_error)
File "/home/lancelot/.local/lib/python3.6/site-packages/pymongo/helpers.py", line 159, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Transaction numbers are only allowed on storage engines that support document-level locking
This is my views function which is catching the post request :
#app.route('/movie', methods = ['GET','POST'])
def add_movie():
movie = mongo.db.movies
try :
name = request.json['name']
print(name)
movie_id = movie.insert({'name':name})
new_movie = movie.find_one({'_id': movie_id })
output = {'name' : new_movie['name']}
return jsonify({'result' : output})
except TypeError:
return jsonify({'result' : 'niet'})
and my POST request is made with an AJAX request in one of my template :
$(document).ready(function() {
$('#movies_btn').click(function() {
$.ajax({
url: "{{ url_for('add_movie') }}",
type: 'POST',
contentType: 'application/json;charset=UTF-8',
data: JSON.stringify({'name':'oui'}),
success: res => {
alert('stop')
window.location.href="{{ url_for('index') }}"
},
error: xhr => {
alert(xhr.responseText.split('\n')[1])
}
})
})
})
Can you help me with this issue? I tried to look at the documentation of flask pymongo but I don't find the answer.
Thanks

alamofire request gets text/html response, while curl and postman get json response

=================================
Note: Using #Larme's trick to print out debugDescription of the request, and comparing with my working curl request, I was able to figure out the dumb bugs I made. 1. In the server request handler, I return a serializerError when something unrecognized, pretty confusing. 2. I made a stupid mistake in my request from swift, putting "GET_RECIPES" instead of "GET_RECIPE".
================================
I have a http service implemented with django rest framework, when I send requests via swift/alamofire, it cannot get the correct json response. However, requests sent via curl and postman get the correct json response.
So I am confused what where is the issue, the django service side or swift request side?
I have tried using .responseString instead of .responseJSON in swift to print out the resposne, but still the data is not in the response, basically the error occurs when the request reaches the server side.
From django server side, the error reads "TypeError: Object of type 'property' is not JSON serializable". OK it seems the issue is from django side...
But from curl and postman, I can get the json response without an issue, with the response header containing "Content-Type": "application/json", and for the django side everything is also OK. Then does this mean the django server can handle json response and it should be the issue of the swift request??
Code in swift,
let parameters: [String: Any] = [
"type": "GET_RECIPE",
"details": ["ingredients" : ["egg", "bread"]]
]
let headers = ["Content-Type": "application/json"]
Alamofire.request(url, mothod: .post, parameters: parameters,
headers: headers, encoding: JSONEncoding.default)
.responseJSON {response in
if let data = response.result.value {
print(data)
}
}
Code of the request handler
class RecipesSerilizer(serializers.ModelSerializer):
class Meta:
model = Recipes
fields = ('id', 'url', 'author', 'category', 'title', 'description',
'instructions', 'tip', 'raw', 'score')
def get_recipes_given_ingredients(data):
logger.info('Get recipes for {}'.format(data.get('details')))
details = data.get('details')
ingredients = details.get('ingredients')
logger.info('GET_RECIPE for ingredients {}'.format(ingredients))
recipes = queries.get_recipe_recommendation_given_ingredients(ingredients)
serializer = RecipesSerilizer(recipes, many=True)
return Response(serializer.data)
Trace stack from the server side:
Internal Server Error: /get-recipes/
Traceback (most recent call last):
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
response = response.render()
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\django\template\response.py", line 106, in render
self.content = self.rendered_content
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\rest_framework\response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\rest_framework\renderers.py", line 733, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\rest_framework\renderers.py", line 688, in get_context
'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\rest_framework\renderers.py", line 424, in get_content
content = renderer.render(data, accepted_media_type, renderer_context)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\rest_framework\renderers.py", line 107, in render
allow_nan=not self.strict, separators=separators
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\rest_framework\utils\json.py", line 28, in dumps
return json.dumps(*args, **kwargs)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\json\encoder.py", line 201, in encode
chunks = list(chunks)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\json\encoder.py", line 437, in _iterencode
o = _default(o)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\site-packages\rest_framework\utils\encoders.py", line 68, in default
return super(JSONEncoder, self).default(obj)
File "C:\Users\Yuanjun\Anaconda2\envs\online_bid\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'property' is not JSON serializable
[14/May/2019 08:29:32] "POST /get-recipes/ HTTP/1.1" 500 124585
i think your problem is that you are trying to send a post to a get request.
try changing your alamofire request as follows:
let parameters: [String: Any] = [
"type": "GET_RECIPE",
"details": ["ingredients" : ["egg", "bread"]]
]
let headers = ["Content-Type": "application/json"]
Alamofire.request(url, mothod: .get, parameters: parameters,
headers: headers, encoding: JSONEncoding.default)
.responseJSON {response in
if let data = response.result.value {
print(data)
}
}
Probably the server crashes while handling your request or cannot find the given URL(because of the trailing slash).
text/html is usually returned if the server has crashed while running in DEBUG mode. This is how it shows the crash reason in a pretty way with the stack trace.
It is really hard to tell what happened in your case. It would be great if you provided the stack trace of the error.

Backend Error (HttpError 500) on Google Search Console API calls (webmasters/v3)

I prepared code that should fetch data from google webmaster console new Web API (v3).
import os
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from apiclient.discovery import build
import googleapiclient
import json
client_email = '<ACCOUNT_IDENTIFIER>#<PROJECT_IDENTIFIER>.iam.gserviceaccount.com'
scopes = ['https://www.googleapis.com/auth/webmasters.readonly',
'https://www.googleapis.com/auth/webmasters']
private_key_path = os.getcwd() + os.path.normpath('/key.p12')
http = httplib2.Http()
credentials = ServiceAccountCredentials.from_p12_keyfile(client_email,
private_key_path,
private_key_password="notasecret",
scopes=scopes
)
http_auth = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', credentials=credentials, http=http_auth)
query_params = {"startDate": "2016-03-01", "endDate": "2016-03-02"}
try:
quered_results = webmasters_service.searchanalytics().query(
key="<KEY>",
siteUrl="http://<SITE_DOMAIN>/",
body=json.dumps(query_params),
fields="rows",
alt="json"
).execute()
print(quered_results)
except googleapiclient.errors.HttpError as e:
print(e)
Execution results with error:
<HttpError 500 when requesting https://www.googleapis.com/webmasters/v3/sites/http%3A%2F%2F<SITE_DOMAIN>%2F/searchAnalytics/query?key=<KEY>&alt=json&fields=rows returned "Backend Error"
The code from above is for authorization with ssh key with p12 format. Key file is correct. Using client_secrets.json end up with the same error, code. The json for error is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "Backend Error",
}
],
"code": 500,
"message": "Backend Error"
}
}
I did connect email to webmaster tools console.
Authorization seems to work since there is no errors for used key/account
Any ideas?
I've noticed that the same error occures when I fetch on https://developers.google.com/apis-explorer with "Request body" improperly set, but I do not see error in JSON I send. BTW It would be nice to have some validation message about that...
Found it! body parameter should actually by python object, not JSON formatted string!
body=json.dumps(query_params),
Should be
body=query_params,