Getting unexpected '#' error under postman Test tab - postman

I am a learner in postman and do not have much experience in programming/scripting.
Here the issue.
Used POST api request - For getting the access token;
Used POST api request - To create an account;
Used POST api request - To cancel an account with CancellationReason
Need to crosscheck the cancellation details (some fields like cancellationReason) in web application.
In order to avoid manually check, i have used GET request api like below
by passing all the mapped fields (as per web application) in the GET request end url
(i.e. by sending the details in fetch_xml query parameter in the end url) in order to get those required fields returned.
Now i got a successful response with status code.
After that i want to compare the fetched values (from the response body) ... VS.... to the data i passed while cancelling the account (i.e. in POST api request - To cancel the account) and make sure both are same.
After that under Test tab - I have updated query like below, however it throwing an Unexpected '#' error (as the below query contains '#' in middle of the field name)
tests["Verify the CancellationReason matches"] = pm.expect(data._usr_cancellationReason_value#OData.Community.Display.V1.FormattedValue).to.eql("CancellationReason");
Can someone please help me to understand whether i should remove this #symbol or should replace with something else ?
Here is the response body:
{
"#odata.context": "https://hfrdcompanies.integrationdev01.crm3.cs.com/api/data/v9.1/$metadata#hfrd_workorders(_usr_cancellationchannel_value,usr_CancellationChannel,_usr_workorderreason_value,usr_WorkOrderReason,hfrd_workorderid,usr_cancellationuser,_usr_cancellationsource_value,usr_CancellationSource,hfrd_name,usr_CancellationChannel(),usr_AccountReason(),usr_CancellationSource())",
"value": [
{
"#odata.etag": "W/\"2345234523\"",
"_usr_cancellationchannel_value#OData.Community.Display.V1.FormattedValue": "Mobile App",
"_usr_cancellationchannel_value": "acefsdflin89-f9jf07-e969f1-a245nk11-00jnfnafn9799fc2a",
"_usr_Accountreason_value#OData.Community.Display.V1.FormattedValue": "Customer Inactive",
"_usr_Accountreason_value": "bde1234522-d45662-e2711-a84561-0007354a2d5c2a",
"hfrd_Accountid": "89025sf3-c668f-e7811-a4331-00asdhh3ab9bd1c",
"usr_cancellationuser": "Testuser08 ABC",
"_usr_cancellationsource_value#OData.Community.Display.V1.FormattedValue": "MOBILE",
"_usr_cancellationsource_value": "6c23asdf-c562-e411-a841-00asdfa",
"hfrd_name": "FP-WK-1000000642"
}
]
}
I want to validate the bold row

Related

How to create a collection variable from response in postman

Selecting a value and right-clicking enables me to save it as a Global variable.
But there is no option to save it as a collection variable.
In the environments section as well. I can see Globals but my collection is not available.
But as I go through blogs/ articles online I can see some variables that are scoped to a collection.
Can I know a way to achieve this?
Tests tab is all you need
Considering the Stackoverflow GetUser API for Reference.
NOTE: The below-shown response is a part of the original response.
Response:
{
"items": [
{
"user_type": "registered",
"user_id": 12345678,
}
]
}
In the above response let's say we need user_type, and user_id in another API's URL / body / headers.
Before accessing we need to store these variables after receiving the response. This can be done in the Tests tab in postman request.
const jsonData = JSON.parse(responseBody);
const userType = jsonData?.items?.[0]?.user_type;
const userId = jsonData?.items?.[0]?.user_id;
if(userType){
pm.collectionVariables.set("userType",userType)
}
if(userId){
pm.collectionVariables.set("userId", userId)
}
Points to Note:
Postman tests are written in Javascript.
Optional chaining in line 2,3 is to avoid console errors. Possible Scenario: When API fails and returns an error response.
The IF Statements are to avoid null values in case of an Error Response. If statements are not mandatory. In fact without using if statements you will get to know clearly that something went wrong.
How to use collection variables
Once you make a request with the above tests. Postman IntelliSense suggests available collection variables. ( Refer to the image attached )
We are sending the body as a raw JSON in this Test Endpoint. Note that userType is surrounded by double quotes "" whereas userId is not. ( JSON syntax )

Postman Mock Server matching algorithm logic for request body param form-data

Is there any option to send mock results depends on form data body value in postman?
I am sending some value in the body as form data and I have two example result and now the mock API return only one example I need to get the result based on the form data value from two examples
I have to call 2 Request with different body values(as form-data) and I need to return json array if the values are correct else I need to return a json object I have saved this two result but while I making mock API it is all ways sending now result only there is no changes in url
Is that possible to send response based on form-data in postman mock api?
I have an api example https://api.exmple.com and i am sending post request wit body form-data and filed check:false or check:true and i need to respond two json based on input filed check false or true how to do it?
When we do with get parameter it is working but not working with body form-data
Updates
I added this in header x-mock-match-request-body:true
Post man responding with this error message
{
"error": {
"name": "mockRequestNotFoundError",
"message": "Double check your method and the request path and try again.",
"header": "No matching requests"
}
}
Update I added postman api key but is not working but when i add x-mock-response-name it is working but i need to x-mock-match-request-body only

Updating Sales Order line items in Dynamics business central

I have a sales order created using API for business central. Sales order has a single line item. I want to update the quantity of line item. Following is what I have tried so far.
Endpoint: https://api.businesscentral.dynamics.com/v1.0/domain.com/api/v1.0/companies(company_id)/salesOrders(sales_order_ide)/salesOrderLines(sales_order_line_id)
where sales order line id is of the form e86d3aa1-f2f8-ea11-aa61-0022481e3b8c-10000
as described in this document When a PATCH request is made, I get the following exception:
')' or ',' expected at position 9 in
'(sale-order-line-item-id)'.
The exception stated above was also occuring when i was simply trying to get the line item but that was fixed when I changed the URL and it took the form:
Endpoint:
https://api.businesscentral.dynamics.com/v1.0/domain.com/api/v1.0/companies(b4a4beb2-2d42-40dc-9229-5b5c371be4e3)/salesOrders(e86d3aa1-f2f8-ea11-aa61-0022481e3b8c)/salesOrderLines?filter=sequence eq 10000
This endpoint is returning correct response when i try to get the line item by issuing
GET request. However, when I issue a PATCH request using the same endpoint, with a simple request body e.g.
{"quantity" : 2.0}
it throws the exception:
'PATCH' requests for 'salesOrderLines' of EdmType 'Collection' are not
allowed within Dynamics 365 Business Central OData web services.
I am also specifying the if-Match header along with the request that contains etag value for the line item but of no avail and same exception is occurring. Am I missing something? Any help will be appreciated.
For those who may visit this question later, after much hit and trial through Postman, I finally figured out the problem. In my case if-Match header that's basically is Etag for the line item is all fine. The Problem was with API URL, specifically the way we specify the line item id. We have to specify this in single quotes so the URL for API call becomes:
https://api.businesscentral.dynamics.com/v1.0/domain.com/api/v1.0/companies(company_id)/salesOrders(sales_order_ide)/salesOrderLines('sales_order_line_id')
You would note that we are not specifying company_id and sales_order_id in single quotes, reason being, both of these parameters a of type GUID whereas sales_order_line_id is of type string as per metadata document.
I am getting below error
{
"error": {
"code": "BadRequest_NotFound",
"message": "Bad Request - Error in query syntax."
}
}

Querying Couchbase Bucket from Postman - Unrecognized parameter in request

Using the Postman tool, I'm trying to query a Couchbase bucket. I'm getting an error response 1065 that there is an "unrecognized parameter in request". The query will work fine within the Couchbase workbench, but I need to be able to do this from Postman.
I'm making a POST request with this body:
{
"statement" : "SELECT * from `myBucketName` where id = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee""
}
There error message is:
"msg": "Unrecognized parameter in request: {\n\"statement\" : \"SELECT from `myBuckeyName` where _id "
I think this is just an issue with how my request body is formatted, I'm just new to this and not sure how it should be formatted based off the error I'm getting.
Here's how I did it:
Open Postman
Select POST
Use a URL of http://localhost:8093/query/service
Under "Authorization", use Basic Auth (with the username/password you've created for Couchbase)
Under "Body", select "x-www-form-urlencoded"
Add a KEY of statement and a value of your query
Click SEND
I got a 200 OK response with the results of the query. Screenshot:
You should definitely check out the Couchbase REST API documentation. It uses curl instead of Postman, but that's a translation you'll eventually get used to.

Instagram Graph API - Fetch media insights metric when a user switched from personal to business account

I'm looking for a way to fetch Media Insights metrics in Instagram Graph API (https://developers.facebook.com/docs/instagram-api/reference/media/insights) with a nested query based on the userId, even when a client switched from a Personal to a Business account.
I use this nested query to fetch all the data I need : https://graph.facebook.com/v3.2/{userId}?fields=followers_count,media{media_type,caption,timestamp,like_count,insights.metric(reach, impressions)} (this part causes the error: insights.metric(reach, impressions) - it works however for an account that has always been a Business one)
However, because some media linked to the userId were posted before the user switched to a Business account, instead of returning the data only for the media posted after, the API returns this error:
{
"error": {
"message": "Invalid parameter",
"type": "OAuthException",
"code": 100,
"error_data": {
"blame_field_specs": [
[
""
]
]
},
"error_subcode": 2108006,
"is_transient": false,
"error_user_title": "Media Posted Before Business Account Conversion",
"error_user_msg": "The media was posted before the most recent time that the user's account was converted to a business account from a personal account.",
"fbtrace_id": "Gs85pUz14JC"
}
}
Is there a way to know, thru the API, which media were created before and after the account switch from Personal to Business? Or is there a way to fetch the date on which the account was switched?
The only way I currently see to get the data I need is to use the /media edge and query insights for each media until I get an error. Then I would get approximately the date I need. However, this is not optimized at all since we are rate limited to 200 calls per user per hour.
I have the same problem.
For now, I'm Switch between queries (if first have error)
"userId"?fields=id,media.limit(100){insights.metric(reach, impressions)}
"userId"?fields=id,media.limit(100)
I show the user all insights in zero.
I don't know if they're the best alternative, like identify the time of conversion to business and get the post between this range of DateTime
I got the same problem and solved it like this:
Use the nested query just like you did, including insights.metric
If the error appears, do another call without insights.metric - to at least get all other data
For most accounts, it works and there is no additional API call. For the rest, i just cannot get the insights and i have to live with it, i guess - until Facebook/IG fixes the issue.
I got the same problem and solved it like this:
Step1: Convert your Instagram account to a Professional account.
Step2: Then According to Error Post a new post on Instagram and get their Post-ID.
Step3: Then try to get a request using that Post-ID.
{Post-ID}?fields=comments_count,like_count,timestamp,insights.metric(reach,impressions)
curl -i -X GET "https://graph.facebook.com/v12.0/{Post-ID}?fields=comments_count%2Clike_count%2Ctimestamp%2Cinsights.metric(reach%2Cimpressions)&access_token={access_token}"
For more: insights
Here is the relevant logic from a script that can handle this error while still doing a full import. It works by reducing the requested limit to 1 once the error is encountered. It will keep requesting insights until it encounters the error again, then removes insights from the fields and returns to the requested limit.
limit = 50
error_2108006 = False
metrics = 'insights.metric%28impressions%29%2C' # Must be URL encoded for replacement
url = '/PAGE_ID/media?fields=%sid,caption,media_url,media_type&limit=%s' % (metrics, limit)
# While we have more pages
while True:
# Make your API call to Instagram
posts = get_posts_from_instagram(url)
# Check for error 2108006
if posts == 2108006:
# First time getting this error, keep trying to get insights but one by one
if error_2108006 is False:
error_2108006 = True
url = url.replace('limit={}'.format(limit), 'limit=1')
continue
# Not the first time. Strip out insights and return to desired limit.
url = url.replace(metrics, '')
url = url.replace('limit=1', 'limit='.format(limit))
continue
# Do something with the data
for post in posts:
continue
# If there are more pages, fetch the next URL
if 'paging' in posts and 'next' in posts['paging']:
url = posts['paging']['next']
continue
# Done
break