WebApi with Odata NextPage and Count not appearing in the JSON response - json

I have a webapi method that I want to switch oData paging etc on.
I followed the example in http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options
My method looks like:
public PageResult<UserViewModel> GetUsers(ODataQueryOptions<UserViewModel> options)
{
var settings = new ODataQuerySettings()
{
PageSize = 2
};
var results = UserLogic.GetUsers(userId, UserManager, _db);
var filtered = options.ApplyTo(results, settings);
var pagedResult = new PageResult<UserViewModel>(
filtered as IEnumerable<UserViewModel>,
Request.GetNextPageLink(),
Request.GetInlineCount());
return pagedResult;
}
That the count is populated and the next page link is there and the correct oData options are applied i.e. sort order etc. When I return it in my api method, the correct data comes back, but the count and next link don't appear in my json.
Am I missing a setting to turn this on?
i.e. this is my json response:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-RequestID: b215962b-6a4a-431d-9850-7ecbf808538e
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcUmVwb3NpdG9yaWVzXEdpdEh1YlxxbGRyYS1wb3J0YWxccWxkcmEtcG9ydGFsLldlYlxxbGRyYS5iYXNlbGluZS5hcGlcYXBpXHVzZXJz?=
X-Powered-By: ASP.NET
Date: Fri, 04 Apr 2014 05:16:53 GMT
Content-Length: 554
[
{
"Id": "500e6f96-b2bd-48d9-8181-5bbc39c673f6",
"UserName": "adam#test.com",
"Organisation": {
"Id": "f179bc35-89b8-e311-9dfd-0050569b4cee",
"Name": "Black and White Cabs Pty Ltd",
"IsActive": true,
"LastUpdatedDate": "2014-04-03T11:35:26.167"
},
"IsLockedOut": false,
"Roles": []
},
{
"Id": "0d661d1b-9e52-4f2f-baec-3eb89197bb6d",
"UserName": "bob#test.com",
"Organisation": null,
"IsLockedOut": false,
"Roles": [
"Service Administrator"
]
}
]

This should work.
Be sure to remove the [EnableQuery] attribute if it is being applied to your method or controller. This will cause the returned JSON to not include the count and next link.

Related

Account linking error: "Can't parse the response. The response needs to be JSON format."

I am attempting account linking within 'Actions on Google'. Everything works until my OAuth provider responds to Google's request for tokens.
This is the JSON that is returned and appears to be properly formatted:
{"access_token":"edeaa27e-12b7-43a1-bc7c-e6bbf9af71c3","expires_in":5184000.0,"refresh_token":"4344383b-cf07-4d12-a5c2-44b6481f5f48","token_type":"Bearer"}
This is the error:
{ "#type": "type.googleapis.com/google.identity.accountlinking.type.AccountLinkingError", "errorReason": "Can't parse the response. The response needs to be JSON format.", "response": { ... }, "step": "AUTH_CODE_EXCHANGE" }
Details:
{
"insertId": "-hgv4mfb4b",
"jsonPayload": {
"#type": "type.googleapis.com/google.identity.accountlinking.type.AccountLinkingError",
"errorReason": "Can't parse the response. The response needs to be JSON format.",
"response": {
"status": 200,
"body": "{\"access_token\":\"cdd79134-316d-46ca-8d82-62fc7c35d905\",\"expires_in\":5184000.0,\"refresh_token\":\"fc63ceb3-0a8d-40ac-a1a3-a8cfab110bef\",\"token_type\":\"Bearer\"}"
},
"step": "AUTH_CODE_EXCHANGE"
},
"resource": {
"type": "assistant_action_project",
"labels": {
"project_id": "my-project"
}
},
"timestamp": "2021-07-30T23:15:28.221Z",
"severity": "ERROR",
"logName": "projects/my-project/logs/accountlinking-pa.googleapis.com%2Ferror",
"receiveTimestamp": "2021-07-30T23:15:28.676796217Z"
}
Here is the response from my OAuth provider via curl. This is what Google gets. It looks like properly formatted JSON.
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Cache-Control: private
Cache-Control: private
< Content-Type: application/json; charset=utf-8
Content-Type: application/json; charset=utf-8
< Vary: Accept
Vary: Accept
< Server: Microsoft-IIS/8.5
Server: Microsoft-IIS/8.5
< Request-Context: appId=cid-v1:f494398c-ac65-47c8-84be-65aea2c190a4
Request-Context: appId=cid-v1:f494398c-ac65-47c8-84be-65aea2c190a4
< X-HOST-nonce: 3eTaf/2/7riVVh24uAsUT+KHqcJPq0F2cw7C5ldMkMF4iH5rDbHQEgOp2OU9RaQFr/HjBBEpkKekcCxlmzek5g==
X-HOST-nonce: 3eTaf/2/7riVVh24uAsUT+KHqcJPq0F2cw7C5ldMkMF4iH5rDbHQEgOp2OU9RaQFr/HjBBEpkKekcCxlmzek5g==
< X-Powered-By: ServiceStack/4.040 Win32NT/.NET
X-Powered-By: ServiceStack/4.040 Win32NT/.NET
< X-AspNet-Version: 4.0.30319
X-AspNet-Version: 4.0.30319
< X-Powered-By: ASP.NET
X-Powered-By: ASP.NET
< Date: Tue, 03 Aug 2021 03:17:00 GMT
Date: Tue, 03 Aug 2021 03:17:00 GMT
< Content-Length: 155
Content-Length: 155
< x-HOST-proxy: true
x-HOST-proxy: true
< Strict-Transport-Security: max-age=15768000
Strict-Transport-Security: max-age=15768000
{"access_token":"6cff16ee-3b3e-4ecf-9664-51515ede6cc8","expires_in":5184000.0,"refresh_token":"03725df6-8d4c-434a-ab36-adedb43b76d7","token_type":"Bearer"}
Google will not accept the 'expires_in' value above, because it includes a decimal. Not sure if this impacts all values with a decimal or just '.0', but the OAuth spec doesn't seem to specifically exclude such a value. Javascript converts any float with just a 0 after the decimal to a whole number. My issue was that the 3rd party OAuth provider was returning a string including a float that Google would not parse as JSON.

Error when trying to decode json: simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I'm receiving this error when trying to decode json:
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Any help will be appreciated.
views.py:
from django.shortcuts import render
import requests
def home(request):
response = requests.get('https://dev-api.prime.com/api/v1/hub/login')
data = response.json()
return render (request, 'home.html', {
'email': data['email'],
'password': data['password']
})
urls.py:
path ('home/', views.home, name="home"),
home.html
{% extends 'main.html' %}
{% block content %}
<h2>API</h2>
<p>Your email is <strong>{{ email }}</strong>, and password <strong>{{ password }}</strong></p>
{% endblock %}
I tried to send POST request from the terminal:
http POST https://dev-api.prime.com/api/v1/hub/login email="sssdprime#gmail.com" password="asssdps"
and get the response I was looking for:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 866
Content-Type: application/json; charset=UTF-8
Date: Wed, 28 Oct 2020 07:09:45 GMT
Server: nginx/1.12.2
Set-Cookie: _language=811f45dc7836f8b3da4c5d04b177501191c20a3f77a46812f864a3bca7d5d3e1a%3A2%3A%7Bi%3A0%3Bs%3A9%3A%22_language%22%3Bi%3A1%3Bs%3A2%3A%22en%22%3B%7D; path=/; HttpOnly
Set-Cookie: _csrf=5f3fb0e6b529660e0a11a97a3fd3e9a85aa3794d20; path=/; HttpOnly
Vary: Accept
X-Debug-Duration: 816
X-Debug-Link: /debug/default/view?tag=5f991938b8410
X-Debug-Tag: 5f991938b8410
X-Frame-Option: SAMEORIGIN
X-Powered-By: PHP/7.2.18
X-UA-Compatible: IE=Edge,chrome=1
X-XSS-Protection: 1
{
"data": {
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDM4Njg5ODUsImlzcyI6Imh0dHA6XC9cL2Rldi1hcGkuZGVudGFwcmltZS5jb206ODA5NCIsImF1ZCI6Imh0dHA6XC9cL2Rldi1hcGkuZGVudGFwcmltZS5jb206ODA58",
"complete": false,
"country": "AL",
"date_of_birth": null,
"email": "sssdprime#gmail.com",
"first_name": "somename",
"id": 201,
"last_name": "somename",
"phone": "08865444567",
"role": 10,
"sf_token": "0014H00002dd",
"type_language": "en",
"username": ""
},
"status": 200,
"success": true
}
This is your request
http POST https://dev-api.prime.com/api/v1/hub/login email="sssdprime#gmail.com" password="asssdps"
While in code,
response = requests.get('https://dev-api.prime.com/api/v1/hub/login')
They are different. In the first request you used "POST" method, with email and password alongside it.
While in your code, you simply ask for "GET" method.
Change request code to something like this, and it should be receiving the correct response.
response = requests.post('https://dev-api.prime.com/api/v1/hub/login', json={"email":"sssdprime#gmail.com", "password":"asssdps"})
and Since the response you want is something like this
{
"data": {
...
},
"status": 200,
"success": true
}
The response will return dictionary. And you only want the data. You need to access the value inside "data" key. So change this,
data = response.json()
into,
data = response.json()['data']

Orion CB: Can't Access Entities via /v2/entities endpoint

While creating a wirecloud wiring using NGSI Source operator, I encountered an error (helpless error) for couple of days, regarding connection to my instance of Orion CB. I can confirm all other NGSI operator settings entered are correct.
Error creating subscription in the context broker server: Connection Error
I however, suspect this error has to do with Orion NOT finding the entities to subscribe the NGSI Source operator. This is because I tried accessing Eindhoven's broker (http://212.159.228.70:1026/) and it works, NGSI Source operator subscription created successfully.
Equally, I get all entities/attributes in the Eindhoven's broker using:
Akil$http http://212.159.228.70:1026/v2/entities
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 15501
Content-Type: application/json
Date: Mon, 13 May 2019 10:20:20 GMT
Fiware-Correlator: b5e5294a-7568-11e9-83c8-0242ac120003
[
{
"NO2": {
"metadata": {},
"type": "Number",
"value": 27.5
},
"Ozon": {
"metadata": {},
"type": "Number",
"value": 59.5
},
"PM1": {
"metadata": {},
"type": "Number",
"value": 8
},
"PM10": {
"metadata": {},
"type": "Number",
"value": 12
},
.
.
}
]
But then I cannot get the entities in my Orion instance using same scenario:
Akil$ http 193.136.xx.xx:53154/v2/entities
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 2
Content-Type: application/json
Date: Mon, 13 May 2019 10:36:13 GMT
Fiware-Correlator: ee22e4b2-756a-11e9-afa1-0242ac160007
[]
Return empty list, whereas I have available 2 FIWARE services: environment and urbansense. The entities I want to access are available with the urbansense fiware-service having /basic fiware-servicepath.
Service health:
Akil$ http 193.136.xx.xx:53154/version
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 345
Content-Type: application/json
Date: Mon, 13 May 2019 10:50:13 GMT
Fiware-Correlator: e32bf3da-756c-11e9-9371-0242ac160007
{
"orion": {
"compile_time": "Tue Feb 12 10:51:10 UTC 2019",
"compiled_by": "root",
"compiled_in": "4f8128ac7b5b",
"doc": "https://fiware-orion.rtfd.io/",
"git_hash": "7ae8c69b97cd875236b952322a6bd503debbd13d",
"release_date": "Tue Feb 12 10:51:10 UTC 2019",
"uptime": "6 d, 18 h, 7 m, 6 s",
"version": "2.1.0-next"
}
}
Questions:
Why can't I access my Orion instance same way I accessed Eindhoven's
broker?
Is this the reason why my wiring for NGSI Source operator
failed, thus reporting subscription error above?
I'm not sure of fully understading your case (specially the relationship with Wirecloud, as I'm not an expert in Wirecloud), but let's try to answer... :)
From:
[GET /v2/entities] Return empty list, whereas I have available 2 FIWARE services: environment and urbansense. The entities I want to access are available with the urbansense fiware-service having /basic fiware-servicepath.
If the entities you want to access are available in a given service and subservice, then you should add then to the GET request. I don't know how the http command works, but if it were curl it would be something like this
curl -H 'fiware-service: environment' and -H 'fiware-servicepath: /basic' http://212.159.228.70:1026/v2/entities

Handling Malformed JSON generated by the Microsoft Academic Knowledge API

Making the following request to the Microsoft Academic gives malformed JSON:
https://westus.api.cognitive.microsoft.com/academic/v1.0/interpret?
query=albert einstein&complete=0&count=2&offset=2&model=latest
The result is as follows
Request-Context: appId=cid-v1:7cd06f0e-6d73-46a5-9c10-4ebe681d0156
apim-request-id: 8eec6818-55d3-4b7c-b1c3-b4c6236f0173
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
x-content-type-options: nosniff
Date: Tue, 31 Oct 2017 01:02:11 GMT
X-Powered-By: ASP.NET
Content-Length: 681
Content-Type: application/json
{
"query": "albert einstein",
"interpretations": [,
{
"logprob": -69.749,
"parse": "<rule name=\"#GetPapers\"><attr name=\"academic#W\">albert</attr> <attr name=\"academic#F.FN\">einstein</attr></rule>",
"rules": [{
"name": "#GetPapers",
"output": {
"type": "query",
"value": "And(W='albert',Composite(F.FN=='einstein'))"
}
}]
},
{
"logprob": -118.575,
"parse": "<rule name=\"#GetPapers\"><attr name=\"academic#W\">albert</attr> <attr name=\"academic#W\">einstein</attr></rule>",
"rules": [{
"name": "#GetPapers",
"output": {
"type": "query",
"value": "And(W='albert',W='einstein')"
}
}]
}
]
}
Notice the leading comma on the third line of the JSON, at the beginning of the interpretations array. I suspect there's a bug in the code used to paginate results. I'm working in Python, and that leading comma breaks every parser I can think of including a straight eval. I think I can handle it with a String.replace before using json.loads, but that's an ugly solution. Are there better alternatives? And am I correct to think this is a bug?

Valid JSON format to share text to a particular contact in Google Glass Mirror API?

I'm playing around with Google Mirror API and creating out some sample apps. Since I'm not an explorer I'm using Sturm's Mirror API.
I'd like to know the valid JSON format to share a piece of text to a particular Google Glass contact. I tried the following JSON in API explorer but got a 400 bad request error. Also is there a way to do the same through Google Glass Playground rather than API explorer?
{
'recipients': [
{
'acceptTypes': [
'text/plain'
],
'displayName': 'myglassapp',
'imageUrls': [
'https://myglassapp.appspot.com/images/welcome.jpg'
],
'id': 'babu_glass_app'
}
],
'kind': 'mirror#timelineItem',
'isDeleted': False,
'text' : 'Hello World',
}
Error:
400 Bad Request
- Hide headers -
cache-control: private, max-age=0
content-encoding: gzip
content-length: 118
content-type: application/json; charset=UTF-8
date: Thu, 30 May 2013 08:05:47 GMT
expires: Thu, 30 May 2013 08:05:47 GMT
server: GSE
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
Oops.. My bad. Python dict to JSON problem. False instead of false. And now the card is getting inserted.
{
'recipients': [
{
'acceptTypes': [
'text/plain'
],
'displayName': 'myglassapp',
'imageUrls': [
'https://myglassapp.appspot.com/images/welcome.jpg'
],
'id': 'babu_glass_app'
}
],
'kind': 'mirror#timelineItem',
'isDeleted': false,
'text' : 'Hello World',
}