I seem to have a syntax problem with my JSON body.
The code is intended to retrieve the balance from LetterXpress using an API, but instead of being able to authenticate, I receive the response:
("{"message":"Unauthorized."}")
The request works fine using Postman.
Here is my C# code:
var client = new RestClient("https://api.letterxpress.de/v2/balance");
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
string jsonString = "{" +
""auth": {" +
""username" : "LXPApi1"," +
""apikey" : "442807b35e250ec767221fe3ba"," +
""mode" : "live"" +
"}" + "}";
request.AddJsonBody(jsonString);
IRestResponse response = await client.ExecuteAsync(request);
string meinString = response.Content;
textBox4.Text = meinString;
With this code, I have tried so far. My suspicion is that the syntax in the jsonString
is incorrect. However, I cannot find the error.
2
Answers
you are building request incorrectly
here is a good call, but not authorized.
still not authorized, as you mentioned – code runs wwith postman request please add a screenshot of postman request
"My suspicion is that the syntax in the jsonString is incorrect." Close, it’s one of the problems with your code.
JSON Encoded String!
AddJsonBody
expects an object that will be serialized automatically – see the documentation. What you’re doing is effectively JSON encoding a string so the request will never be able to deserialize it to your expectations.What you should be doing instead is pass an object that has all the expected properties. You can use an anonymous object, or a concrete class, for the request body:
GET Request With Body
You’re sending a GET request and attempting to include a body with the request which is not valid for GET requests. The chances are that you should be sending a POST request instead.
Unfortunately the API Documentation (in German) shows a GET request which most, if not all, HTTP clients will not support and are likely to not include the body of the request even though you have set it.
Side Notes