how to specify certain field which is inside array in restapi - api

I have an api link https://apilink.com?_fields=id,name,images which gives me the following format
[
{
"id": 229210,
"name": "Basic Electrical Knowledge",
"images": [
{
"id": 229211,
"date_created": "2023-01-13T18:34:39",
"date_created_gmt": "2023-01-13T07:34:39",
"date_modified": "2023-01-13T18:34:39",
"date_modified_gmt": "2023-01-13T07:34:39",
"src": "https://sampleSite.in/wp-content/uploads/2023/01/SomeUrlSource.jpg",
"name": "Basic Electrical Knowledge",
"alt": ""
}
]
}
]
I want to access only src from images[]. How do I retrieve this from the link. When clicking the link I want to display this:
[
{
"id": 229210,
"name": "Basic Electrical Knowledge",
"src": "https://sampleSite.in/wp-content/uploads/2023/01/SomeUrlSource.jpg"
}
]
How do I do this?
I tried to solve this by providing this parameters:
https://apilink.com?_fields=id,name,images=src

You can achieve this by making a GET request to the API link and then using a library such as JSON.parse() to parse the response and extract the necessary data. After that, you can use a for loop to iterate over the 'images' array in the response and extract the 'src' key from each object in the array. Finally, you can construct a new object with the desired format and return it.
fetch(https://apilink.com?_fields=id,name,images)
.then(response => response.json())
.then(data => {
let newData = []
data.forEach(item => {
let newItem = {
id: item.id,
name: item.name,
src: item.images[0].src
}
newData.push(newItem)
});
return newData;
})
.then(newData => {
console.log(newData);
});
Note that this code snippet is simplified and doesn't handle errors, it's only serve as an example of how you could do it.

Assuming that you can't make server-side changes, implement a little script, and want the result just manipulating the URI the response is no.
The URI is referring to a resource in the server, the _fields seem like a projection to make to the attributes of the desired resource.
In this case, you are trying to make a transformation on the resource given by the server through. If the server does not implement such functionality you must do it by yourself.
You want to transform the attribute images that has type [Object] to a String.
A code snippet like the answered by #RASIKA EKANAYAKA would fit your requirement.

Related

Change custromer-request-type in Jira ServiceDesk via REST API

I can receive the values of an created ticket using the SD API like:
GET /servicedeskapi/request/SD-4532
and within that i find something like:
{
"issueId": "71928",
"issueKey": "SD-4532",
"requestTypeId": "121",
"serviceDeskId": "5",
...
}
whereas "requestTypeId" related to the type created by the user (e.g. has a label "Common question").
Now i want to change the request type to, let's say "Hardware issue" which have the requestTypeId of "89".
When i try to change by POST /servicedeskapi/request/SD-4532
and giving a payload of
{
"requestTypeId": "89",
}
I get a "405 - Method not allowed". Also the Jira ServiceDesk REST-API doc does not state anything about a POST method for this.
So i tried the common Jira REST-API
PUT /api/2/issue/SD-4532
and give payload
{
"fields": {
"customfield_10001": {
"requestType": {
"id": "89"
}
}
}
}
but that give me an "Field 'customfield_10001' cannot be set. It is not on the appropriate screen, or unknown." error.
The reason why the Jira ServiceDesk REST API docs do not state anything about a POST method for this because.... there is no POST method for this. You cannot change a request (issue) type simply by altering the value of the field that contains the ID (metadata) of that request type.
Do a Google search on "jira rest api change issue type" to see the many other times this question has been discussed in the past in many places. In a nutshell, changing types is not possible via the REST API, only the web UI.
Use Jira Rest API to update Jira issue information. https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issues/#api-rest-api-3-issue-issueidorkey-put
// This code sample uses the 'node-fetch' library:
// https://www.npmjs.com/package/node-fetch
const fetch = require('node-fetch');
const bodyData = `{
"fields": {
"customfield_10010": "ABC-09",
"customfield_10000": {
"air": "",
"type": "doc",
"name": "Sample Process",
"avatarUrl": null
}
}
}`;
fetch('https://your-domain.atlassian.net/rest/api/3/issue/{issueIdOrKey}', {
method: 'PUT',
headers: {
'Authorization': `Basic ${Buffer.from(
'email#example.com:<api_token>'
).toString('base64')}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: bodyData
})
.then(response => {
console.log(
`Response: ${response.status} ${response.statusText}`
);
return response.text();
})
.then(text => console.log(text))
.catch(err => console.error(err));
email#example.com --> Your Jira emailid
<api_token> --> This is from your account token generated
Note:- Before using any API check if it's not experimental as this may cause issues in future due to sudden change in req/resp from Jira.
Try to inspect Jira dashboard network tab to understand more.

Is it possible to read google sheets *metadata* only with API key?

It is possible to read data from a sheet only with API key (without OAuth 2.0), but it seems that reading the developer metadata requires OAuth 2.0.
Is there some way to read the metadata from an app without asking the user to connect his google account?
You want to retrieve the developer metadata of the Spreadsheet using the API key.
You have already been able to get values from Spreadsheet using the API key.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Issue and workaround:
Unfortunately, "REST Resource: spreadsheets.developerMetadata" in Sheets API cannot be used with the API key. In this case, OAuth2 is required as mentioned in your question. The developer metadata can be also retrieved by the method of spreadsheets.get in Sheets API. The developer metadata can be retrieved by the API key. And in this method, all developer metadata is retrieved. So when you want to search the developer metadata, please search it from the retrieved all developer metadata.
IMPORTANT POINTS:
In this case, please set the visibility of developer metadata to DOCUMENT. By this, the developer metadata can be retrieved by the API key. If the visibility is PROJECT, it cannot be retrieved with the API key. Please be careful this.
When you want to retrieve the developer metadata with the API key, please publicly share the Spreadsheet. By this, it can be retrieved with the API key. Please be careful this.
Sample situation 1:
As a sample situation, it supposes that it creates new Spreadsheet, and create new developer metadata to the Spreadsheet as the key of "sampleKey" and value of "sampleValue".
In this case, the sample request body of spreadsheets.batchUpdate is as follows.
{
"requests": [
{
"createDeveloperMetadata": {
"developerMetadata": {
"location": {
"spreadsheet": true
},
"metadataKey": "sampleKey",
"metadataValue": "sampleValue",
"visibility": "DOCUMENT"
}
}
}
]
}
Sample curl command:
When you retrieve the developer metadata from above sample Spreadsheet, please use the following curl command.
curl "https://sheets.googleapis.com/v4/spreadsheets/### spreadsheetId ###?key=### your API key ###&fields=developerMetadata"
In this case, fields=developerMetadata is used to make it easier to see the response value. Of course, you can also use * as fields.
In this case, when above endpoint is put to the browser, you can see the retrieved value, because of GET method.
Result:
{
"developerMetadata": [
{
"metadataId": 123456789,
"metadataKey": "sampleKey",
"metadataValue": "sampleValue",
"location": {
"locationType": "SPREADSHEET",
"spreadsheet": true
},
"visibility": "DOCUMENT"
}
]
}
Sample situation 2:
As other situation, it supposes that it creates new Spreadsheet, and create new developer metadata to the 1st column (column "A") as the key of "sampleKey" and value of "sampleValue".
In this case, the sample request body is as follows.
{
"requests": [
{
"createDeveloperMetadata": {
"developerMetadata": {
"location": {
"dimensionRange": {
"sheetId": 0,
"startIndex": 0,
"endIndex": 1,
"dimension": "COLUMNS"
}
},
"metadataKey": "sampleKey",
"metadataValue": "sampleValue",
"visibility": "DOCUMENT"
}
}
}
]
}
Sample curl command:
When you retrieve the developer metadata from above sample Spreadsheet, please use the following curl command.
curl "https://sheets.googleapis.com/v4/spreadsheets/### spreadsheetId ###?key=### your API key ###&fields=sheets(data(columnMetadata(developerMetadata)))"
In this case, sheets(data(columnMetadata(developerMetadata))) is used to make it easier to see the response value. Of course, you can also use * as fields.
Result:
{
"sheets": [
{
"data": [
{
"columnMetadata": [
{
"developerMetadata": [
{
"metadataId": 123456789,
"metadataKey": "sampleKey",
"metadataValue": "sampleValue",
"location": {
"locationType": "COLUMN",
"dimensionRange": {
"dimension": "COLUMNS",
"startIndex": 0,
"endIndex": 1
}
},
"visibility": "DOCUMENT"
}
]
},
{},
,
,
]
}
]
}
]
}
References:
Method: spreadsheets.developerMetadata.get
DeveloperMetadataVisibility
If I misunderstood your question and this was not the direction you want, I apologize.

How to post event with metadata to stream through HTTP API

I'm using EventStore and want to post a message (event) to it. I use the HTTP API for testing purposes. I've managed to post the event itself, with an event type specified, but I can't figure out how to specify metadata for my event. (and I must provide this metadata because my consuming application on the other side expects it).
This is what my HTTP request looks like:
Content-Type: application/json
ES-EventType: My.own.event.type
POST http://10.0.75.2:2113/web/index.html#/streams/foobar
{
"props": "andvalues"
}
Do I specify metadata in the body in through headers? I can't find much docs about this, only the official that doesn't mention it.
The documentation mentions the full schema for an event being written. It looks like this:
[
{
"eventId" : "string",
"eventType" : "string",
"data" : "object",
"metadata" : "object"
}
]
For example:
[
{
"eventId": "fbf4a1a1-b4a3-4dfe-a01f-ec52c34e16e4",
"eventType": "event-type",
"data": { "a": "1" },
"metadata": { "b": "2" }
}
]
Note that it's an array, and that you must pass content-type as application/vnd.eventstore.events+json
Check this page, scroll to Event Store Events Media Type.

CakePHP3.4: How to send a json object response?

I try to migrate to 3.4 and I have a problem to send a json object.
Up to 3.3, I used the following code:
$jsonSites = json_encode([
'reqLocation' => [
'latitude' => $latitude,
'longitude' => $longitude
],
'sites' => $sitesList,
'discoveryBooks' => $discoveryBooksList,
'deleteSites' => !empty($inDeviceSites) ? [$inDeviceSites] : [],
'deleteBooks' => !empty($inDeviceBooks) ? [$inDeviceBooks] : []
]);
$this->response->type('application/json');
$this->response->body($jsonSites);
And my client received such kind of object:
{
"reqLocation": {
"latitude": 48.080563,
"longitude": 4.4649
},
"sites": [
{
"id": 5076,
"name": "...",
"modified": "2017-01-28T03:03:23+00:00",
"directory_name": "fr/26/26120_56cc30ea4d907",
"type": "portail",
"longitude": 7.031953,
"latitude": 47.939468,
"image_0": "jpg",
"picto_color": "#FFDDDDDD",
"agthemes": [],
"distance": 131.29188575851,
"category": 1281,
"category_name": "Jardin",
"sitecategories": [
{
"id": 10,
"code": 1281,
"name_fr": "Jardin",
"_joinData": {
"id": 1876,
"site_id": 5076,
"site_category_id": 10,
"authorized": true
}
},
{
"id": 33,
"code": 1283,
"name_fr": "Jardin botanique",
"_joinData": {
"id": 5693,
"site_id": 5076,
"site_category_id": 33,
"authorized": true
}
}
]
},
],
"discoveryBooks": [],
"deleteSites": [],
"deleteBooks": []
}
So now I just replaced the deprecated Response methods like that:
EDIT: Of course I return the response object but that cannot work like done here!
$this->response->withType('application/json');
$this->response->withStringBody($jsonSites);
return $this->response;
But now my client doesn't receive anything. I also tried with postman, nothing!
What's wrong?
Check the migration guide, the new reponse methods follow the PSR-7 immutability pattern.
Request & Response Deprecations
The bulk of deprecations for 3.4 are in the Request and Response
objects. The existing methods that modify objects in-place are now
deprecated, and superseded by methods that follow the immutable object
patterns described in the PSR-7 standard.
Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Request & Response Deprecations
Adopting Immutable Responses
Before you migrate your code to use the new response methods you
should be aware of the conceptual differences the new methods have.
The immutable methods are generally indicated using a with prefix. For
example, withLocation(). Because these methods operate in an immutable
context, they return new instances which you need to assign to
variables or properties. If you had controller code that looked like:
$response = $this->response;
$response->location('/login')
$response->header('X-something', 'a value');
If you were to simply find & replace method names your code would break.
Instead you must now use code that looks like:
$this->response = $this->response
->withLocation('/login')
->withHeader('X-something', 'a value');
There are a few key differences:
The result of your changes is re-assigned to $this->response. This is
critical to preserving the intent of the above code. The setter
methods can all be chained together. This allows you to skip storing
all the intermediate objects.
Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Adopting Immutable Responses
Long story short, in your case you must return the new request object created by the immutable methods:
return $this->response
->withType('application/json');
->withStringBody($jsonSites);
If you wouldn't return a response object, then you'd need to reassign the new reponse to $this->response as mentioned in the above quote.

aurelia-http-client connects to wrong address

I have a problem with the aurelia Http Client.
My api (http//localhost:3000/api/posts) works fine. The output of a get call (in postman or in the browser) is:
[
{
"_id": "58a5f4f635c3ab643c74d97a",
"text": "Foo",
"name": "Fooo",
"__v": 0
},
{
"_id": "58a5fcc32586d0683455f78d",
"text": "Bar",
"name": "Baar",
"__v": 0
}
]
This is my get call in the aurelia app:
getPosts(){
return client.get('http//localhost:3000/api/posts','callback')
.then(data => {
console.log(data);
return data.response;
})
}
And this is the output:
As you can see in the image the response contains something with "Aurelia" but my api never touched aurelia so i think there is something wrong with the URL.
Update1:
The fix suggested by GManProgram (missing :) was the problem.
Update2:
I have changed to the client to the aurelia-fetch-client as GManProgram suggested.
Here is the new output
I seems to put the address from the api behind its own address. Ho can I force it only to use the api address?
So first things first, in the example you posted, you are missing the : character after http in the URL.
If that doesn't fix it, and you are using the HttpClient from aurelia-fetch-client, then you may want to try using the .fetch method instead of the .get method
http://aurelia.io/hub.html#/doc/api/aurelia/fetch-client/1.1.0/class/HttpClient
In your case, since it looks like you are expecting json, the typical fetch call would look like:
return this.httpClient.fetch('http://localhost:3000/api/posts')
.then(response => response.json())
.then(response => new CaseModel(response));
Where you can also import the json method from aurelia-fetch-client.
Otherwise, maybe the HttpClient has already been configured in the application with a base URL and it is screwing you up?
What about:
return client.get('posts','callback')