Whenever I attempt to make a PUT Request to Reddit API in order to add a friend, it fails and claims a JSON Parse Error 'JSON_PARSE_ERROR'. Nothing I do is working. Here is how I form the request.
Endpoint: /api/v1/me/friends/username
>>> Endpoint URL: PUT https://oauth.reddit.com/api/v1/me/friends/micheal
Authorization: Bearer <Access_Token>
// The response given:
{"fields": ["json"], "explanation": "unable to parse JSON data", "reason": "JSON_PARSE_ERROR"}
I have also tried the /api/friend/username endpoint and nothing works.
I had exactly the same problem, and your question led me to the solution.
The endpoint is expecting a json payload ACTUALLY NAMED "json." I'm not sure what language you're using, this is what it looks like in Node:
var options = {
url: 'https://oauth.reddit.com/api/v1/me/friends/mynewfriend',
headers: {
'User-Agent': 'Appname/1.0 by username',
'Authorization': "bearer " + <Access_Token>
},
json: {
'name': 'mynewfriend',
'notes': 'whatever notes you want to put',
}
};
request.put(options, function(error, response, body) {
blah blah blah
}
the json itself is described in https://www.reddit.com/dev/api/#PUT_api_v1_me_friends_{username}
Related
What is the right format of the Response for Kinesis Firehose with http_endpoint as destination. Have already gone through the aws link:
https://docs.aws.amazon.com/firehose/latest/dev/httpdeliveryrequestresponse.html#responseformat
I have used the below lambda code in python(integrated in api) as well as with many other options, but keep getting the below error message. The test is performed using the "Test with Demo Data" option
sample code:
def lambda_handler(event, context):
data ={}
headersD = {}
headersD['content-length'] = 0
headersD['content-type'] = 'application/json'
data['requestId'] = 'ed4acda5-034f-9f42-bba1-f29aea6d7d8f'
data['timestamp'] = '1578090903599'
bodyDetail= {}
data['body'] = ''
data['headers'] =headersD
data['statusCode']=200
resp = json.dumps(data)
return resp
error response as seen in the logs:
The response received from the endpoint is invalid. See Troubleshooting HTTP Endpoints in the Firehose documentation for more information. Reason:. Response for request 'request-Id' is not recognized as valid JSON or has unexpected fields. Raw response received: 200 "HttpEndpoint.InvalidResponseFromDestination"
Here is the sample output that worked(in python):
responseBody = {
"requestId": "requestId",
"timestamp": 123456
}
resp = {
"headers": {"Content-Type": "application/json", "Content-Length": 100},
"body": json.dumps(responseBody),
"statusCode": 200
}
return resp
I am making POST request using http lib in Dart. After I wandering around former answers with no luck. Even official doc
import 'package:http/http.dart' as http;
Future<http.Response> createAlbum(String nameEN) {
return http.post(
'http://localhost:8000/api/products/',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'nameEN': nameEN,
}),
);
}
And I test with unittest like this
testWidgets('POST request from offcial docs', (WidgetTester tester) async{
final http.Response res = await createAlbum("Jordan");
print(res.statusCode);
});
Attempt:
PostmanApp can make request and get 201 in response. However, when I copy&paste the Dart code from it and test it does not work
I always get 400 and no request comes to localhost:8000
testWidgets('POST request from postman', (WidgetTester tester) async{
var headers = {
'Content-Type': 'application/json'
};
var request = http.Request('POST', Uri.parse('localhost:8000/api/products/'));
request.body = '''{\n "name_jp": "李天宝",\n "name_en": "Sarit",\n "description": "Developer",\n "qty": 3,\n "expiry": "2099-12-25",\n "barcode": "549XXXYYYYYY",\n "price": "{\\"bounds\\": \\"[)\\", \\"lower\\": \\"12\\", \\"upper\\": \\"6\\"}",\n "medium_price": 60\n}''';
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(200);
print(await response.stream.bytesToString());
}
else {
print(response.statusCode);
print(response.reasonPhrase);
}
});
Problem
Dart response returned to me is 400 and on the server side request has not been sent out to my http://localhost:8000/api/products/
Question:
What is the correct POST syntax?
References:
HTTP POST with Json on Body - Flutter/Dart
Bad state: Cannot set the body fields of a Request with content-type "application/json"
Flutter FormatException: Unexpected character (at character 1)
Http POST request with json content-type in dart:io
You have non-ASCII characters. Did you set the proper ; charset=UTF-8 in your Content-Type header? Or even better, JSON doesn't understand non-ASCII unless you \u encode them.
Lesson learnt here
Add CORS enable in chrome
flutter run -d web. Do not use -d chrome
Make request from cors enabled chrome by clicking. Do not use unittest!
I try to search items from eBay API. Within the server.js file at my Apollo Server 2, I pass the token string by context property while instantiation (s. Doku: Apollo context argument). So every request contains the authentication HTTP header property. As a tryout, for now, I just use the fixed token string. This will be changed later if I work for the client.
server.js
import { ApolloServer } from 'apollo-server'
import schema from './schema'
const server = new ApolloServer({
schema,
context: ({ req }) => {
const token = 'Bearer v^1.1#i^1#I^3#f^0#p^1#r^0#t^H4sIAAA...' // my token
return {
...req,
headers: {
...req.headers,
// enrich the header with oauth token
authorization: token,
},
}
},
})
server.listen().then(({ url }) => console.log(`🚀 Server ready at ${url}`))
resolver method
// A map of functions which return data for the schema.
const resolvers = {
Query: {
books(root, { keyword = '' }, context) {
console.log(context.headers)
fetch(`https://api.ebay.com/buy/browse/v1/item_summary/?q=${keyword}`)
.then(response => response.json())
.then(json => console.log(json))
return []
}
}
}
The context.header contains the authorization property:
{ host: 'localhost:4000',
connection: 'keep-alive',
'content-length': '108',
accept: '*/*',
origin: 'http://localhost:4000',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
dnt: '1',
'content-type': 'application/json',
referer: 'http://localhost:4000/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'de,en;q=0.9',
authorization: 'Bearer v^1.1#i^1#f^0#p^1#r^0#I^3#t^H4sIAAAAAAAAAOV...'
}
The JSON response contains the error with errorId 1002. It says Access token is missing in the Authorization HTTP request header.:
{ errors:
[ { errorId: 1002,
domain: 'OAuth',
category: 'REQUEST',
message: 'Missing access token',
longMessage: 'Access token is missing in the Authorization HTTP request header.' } ] }
Additionally, I use a new browser tab, enter the URL https://api.ebay.com/buy/browse/v1/item_summary/search?q=test and add the same authorization header property (I use the ModHeader chrome extension). I hit enter, the request works and I get the expected JSON.
It is confusing and I don't know what I'm doing wrong while passing the token. Does somebody have an idea?
The headers you see are the ones being sent in the request to your GraphQL server. All you've done is modified them to include the Authorization header and then included your entire request object as your context -- you're not passing any header information to the fetch call actually getting the data from eBay. Minimally, you want to do something like this:
fetch(`https://api.ebay.com/buy/browse/v1/item_summary/?q=${keyword}`, {
headers: {
Authorization: context.headers.authorization,
},
})
Also bear in mind that the fetch call should be returned inside your resolver, otherwise it won't be awaited.
I am getting below errors while trying to create workitems with batch creation method
Error 1
"Message":"No MediaTypeFormatter is available to read an object of type 'JsonBatchHttpRequest' from content with media type 'application/json-patch+json'."
Error 2
{"count":1,"value":{"Message":"One or more errors occurred."}}
I have referred to this documentation https://www.visualstudio.com/en-us/docs/integrate/api/wit/batch from Microsoft . and my question on stackoverflaw Create Large Amount of Work Items in TFS Using Javascript REST API
I have tried to send data as below methods
"json: x"
"body: x:"
"body:JSON.stringify(x)"
"json:[body:x]"
I have tried both "application/json-patch+json" and "application/json"(recommended as MIcrosoft documentation) as Content-Types
I have tired both Post (recommended as MIcrosoft documentation) and Patch methods
There is no references available for this error hence I have sucked at this point.What could be possibly wrong here please help..
public batchOperation( ):q.Promise<boolean>{
let deferred = q.defer<boolean>();
try {
var batchCreateUrl = this.collectionURL+"/_apis/wit/$batch?api-version=1.0";
var x= {
method:"PATCH",
uri:"/VSTS_TFS_Test/_apis/wit/workItems/$Bug?api-version=1.0",
headers:{
"Content-Type":"application/json-patch+json"
},
body:[
{ "op":"add",
"path": "/fields/System.Tags",
"value":"tg;tg1;tg2"
},
{
"op": "add",
"path": "/fields/System.Title",
"value": "Some Title Text "
},
{
"op": "add",
"path": "/fields/System.Description",
"value":"this is description"
}
]
}
var options = {
url: batchCreateUrl,
username: this.username,
password: this.password,
domain: this.domain,
method: 'PATCH',
headers: {
'Content-Type': 'application/json-patch+json'
},
body: x
};
httpntlm.patch(options, function(err,res) {
if(err) {
return deferred.reject(false);}
else{
console.log("Patch Complete");
console.log(res.body);
deferred.resolve(true);
}
});
} catch (error) {
console.log("Failed to Perform Batch Operation ")
deferred.reject(false);
}
return deferred.promise;
}
You need to use "application/json" as Content-Types and the post method just like the tutorial of Microsoft documentation described.
Since you are using httpntlm, you can include the following options:
json: if you want to send json directly (content-type is set to
application/json)
files: an object of files to upload (content-type is set to
multipart/form-data; boundary=xxx)
body: custom body content you want to send. If used, previous
options will be ignored and your custom body will be sent.
(content-type will not be set)
Source Link
If you are using body, your previous options will be ignored(content-type will lose), this may cause the issue. Give a try with directly using json.
I'm trying to delete an entry from the database by odata. I get the error message
{"error":{"code":"","message":{"lang":"en-US","value":"Bad Request - Error in query syntax."}}}
my code:
function deleteMonthEntry() {
var item = actMonthEntries.getItem(listIndex);
var queryString = "Stundens(" + item.data.datensatz_id + ")?$format=json";
var requestUrl = serviceUrl + queryString;
WinJS.xhr({
type: "delete",
url: requestUrl,
headers: {
"Content-type": "application/json"
}
}).done(
function complete(response) {
},
function (error) {
console.log(error);
}
);
}
My request URL looks like this:
requestUrl = "http://localhost:51893/TimeSheetWebservice.svc/Stundens(305233)?$format=json"
Thanks
Marlowe
At least I found the solution:
I've entered an filter request to my service like this:
TimeSheetWebservice.svc/Stundens?$filter=datensatz_id eq 305221
this returned the correct entry with this link:
TimeSheetWebservice.svc/Stundens(305221M)
So if I enter a M after the ID, everything works fin. But I have no idea where this M comes from.
Can anyone tell me the reason for this M? It does not belong to the ID. The ID is this
305221
Marlowe
Are you sure the server you're talking to supports the $format query option? Many don't. I would try removing that part of the request URI, and instead modify your headers value to specify an Accept header:
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
For servers where $format is allowed, giving it a json value is equivalent to providing an Accept header with the application/json MIME type.
In general, for a DELETE operation, the Accept header or $format value only matters for error cases. With a successful DELETE, the response payload body will be empty, so there's no need for the server to know about your format preference.