Restful Uri structure to get array of resources of same type with only limited fields in response? - rest

We have following API to get the list of all versions of cars in our database. A particular version can have multiple colour options available.
GET /api/versions/
[
{
"id": 1,
"colors": [{"name":"red", "hex": "#ff0000"},{{"name":"blue", "hex": #0000ff}}], //array of colors of that version
"price": 10000
},
{
"id": 2,
"colors": [{"name":"red", "hex": "#ff0000"},{{"name":"blue", "hex": #0000ff}}], //array of colors of that version
"price": 20000
},
...
]
The client wants an API to get NOT ALL but multiple versions data and only the colour field. What should be the URI for such a requirement? I have thought of something like below but I am not sure:
To get colors of version id 8 and 9:
GET /api/versions/?fields=colors&id=8,9
[
{
"id": 8,
"colors": [{"name":"tui", "hex": "#gg0000"},{{"name":"rie", "hex": #or0000}}], //array of colors of that version
},
{
"id": 9,
"colors": [{"name":"rie", "hex": "#or0000"},{{"name":"tui", "hex": #gg0000}}], //array of colors of that version
}
]
Please note: I have oversimplified things here. Versions response is quite complex and contains many more fields other than id, colours and price mentioned above. Plus, we will get multiple such requirements like we have got for colour currently i.e. to get the price of multiple versions.

The query parameters you have specified are perfect!
If you have unique ids for cars which can become a part of your api endpoint like
/api/cars/$car_id/versions?fields=colors,price&ids=8,9
Or you can try using /api/carversions instead of /api/versions.
You can also refer my answer to a similar question

Related

Woocommerce REST API display attributes meta_data as slugs

I rely on the Woocommerce REST API for a couple different purposes—one is through the shipping platform ShippingEasy and the other is a custom solution to get order information into a google spreadsheet. When retrieving the order information, I have noticed that variable product attributes are coming over as the slugs and not as the case sensitive names.
To make sure there were no bugs or conflicting plugins I performed a clean install, added a couple test products, then pulled the orders using postman via the API. Sure enough Woocommerce serves the slug as the value instead of the name. Here is a small sampling of what is returned from the GET
"line_items": [
{
"id": 3,
"name": "Test Product - Black, Small",
"product_id": 26,
"variation_id": 29,
"quantity": 1,
"tax_class": "",
"subtotal": "6.00",
"subtotal_tax": "0.00",
"total": "6.00",
"total_tax": "0.00",
"taxes": [],
"meta_data": [
{
"id": 29,
"key": "pa_color",
"value": "color-black"
},
{
"id": 30,
"key": "pa_size",
"value": "size-small"
},
{
"id": 31,
"key": "Clip ($5.00)",
"value": "Upgrade"
}
],
"sku": "TEST",
"price": 6
}
],
As you can see, under "meta_data", "key" (the attribute name) is showing the slug and "value" (selected attribute term) is also showing the slug. You may note "id" 29 and 30 are both global attributes, so it is appending the pa_ value to the "key" as well. What is interesting is that if you create the attribute locally (within the product listing), the GET shows the "meta_data" "key" as the slug, but the "value" will show as the case sensitive name. You may note that "id" 31 is displaying both the "value" and "key" with the case sensitive names—these are coming from the Add-ons plugin.
It seems that the meta_data "key" and "value" should be able to display as the case sensitive name. Is it possible this could be resolved using a function within functions.php?
It now looks like the API provides display_key and display_value within the meta_data, which returns the name instead of the slug for each. Oddly enough this is not yet in the API documentation and must be a recent addition, which I stumbled across from testing a random GET request.

Trouble with variable in Postman POST request

I am very new to coding, so my apologies if I use the wrong terms or am unclear. I have a list of 400+ words I need to be able to enter into my database. I found this collection to loop through my data and post it to the database. I am able to mostly get it to work, except for this one section (the meanings section) where it's an array of objects. If it makes a difference, this is for a React project and using MongoDB for the database.
Each word looks like this:
{
"text": "happy",
"traits": [
"wordlist100"
],
"meanings": [
{
"meaning": "happy",
"category": "default"
}
],
"approved": true,
"createdby": "60dcd7ba69b1e52ac8138051",
"approvedBy": "60dcd7ba69b1e52ac8138051",
"lastUserEdit": "60dcd7ba69b1e52ac8138051",
"blocked": false
}
Where each word can have multiple traits and multiple meanings.
I have all the words in a JSON file, and am running it through Postman using the collection linked above. This is the body of my request in Postman:
{
"text": "{{text}}",
"traits": [
"{{traits}}"
],
"meanings": [
{
"meaning": "{{meaning}}",
"category": "{{category}}"
}
],
"approved": true,
"createdby": "60dcd7ba69b1e52ac8138051",
"approvedBy": "60dcd7ba69b1e52ac8138051",
"lastUserEdit": "60dcd7ba69b1e52ac8138051",
"blocked": false
}
Using this, everything comes through correctly in my database except for the meaning and category of a word. This is what shows up in MongoDB:
{
"_id": {"$oid": "6121bd6addff936ba4eb84bf"},
"traits": [
"wordlist100"
],
"text": "happy",
"meanings": [
{
"_id": {"$oid": "6121bd6addff936ba4eb84c0"},
"meaning": "{{meaning}}",
"category": "{{category}}"
}
],
"approved": true,
"createdBy": {"$oid": "60dcd7ba69b1e52ac8138051"},
"approvedBy": {"$oid": "60dcd7ba69b1e52ac8138051"},
"lastUserEdit": {"$oid": "60dcd7ba69b1e52ac8138051"},
"blocked": false,
"createdAt": {"$date": "2021-08-22T02:58:50.679Z"},
"updatedAt": {"$date": "2021-08-22T02:58:50.679Z"},
"__v": 0
}
What am I doing wrong with the meanings section of the word? I tried playing around with several combinations of brackets and such for how to set up the meanings part.
I did try:
"meanings": [
"{{meanings}}"
]
...but that didn't work at all. Most of what I tried created an error that stopped the collection from running at all (it was probably bad syntax, as I said, I'm really new). This is the only arrangement that seems to get me close to right. Any help would be greatly appreciated.
Thanks!!
Attaching pics of the Postman code and created MongoDB document if it's easier for any of you to look at it with that formatting:
Image of Postman code
Image of MongoDB document created
So I feel foolish and this just shows how new I am to all of this. When I posted this question, all I had done was to try copying the style of what I saw in the body text of the example I found (linked in my question), but didn't do anything with actually defining variables or touching the pre-request script because I didn't realize that was a separate step. So basically, I just got lucky that it was smart enough to figure out the other values without me defining them as variables.
If anyone is reading this later, here's 3 pages of documentation I used to help me figure out my errors: Using Variables, Importing Data Files, and Scripting in Postman.
From reading those, I added the following code in the pre-request script:
let meanings = pm.iterationData.get("meanings");
pm.variables.set("meaning", meanings[0].meaning);
pm.variables.set("category", meanings[0].category);
I also set "meaning" and "category" as named variables with no initial value in the collection.
Image of adding variables to the Postman collection
One caveat I should note is that I'm not certain how well this will work once I start entering stuff with more than one trait or more than one meaning, because I haven't tested those parts yet. I suspect I still need to tweak things to make it work under those instances. But it is working in the examples I have with just one trait and one object in the meanings array.

Generate a JSON schema from an existing MongoDB collection

I have a MongoDB collection that contains a lot of documents. They are all roughly in the same format, though some of them are missing some properties while others are missing other properties. So for example:
[
{
"_id": "SKU14221",
"title": "Some Product",
"description": "Product Description",
"salesPrice": 19.99,
"specialPrice": 17.99,
"marketPrice": 22.99,
"puchasePrice": 12,
"currency": "USD",
"color": "red",
},
{
"_id": "SKU14222",
"title": "Another Product",
"description": "Product Description",
"salesPrice": 29.99,
"currency": "USD",
"size": "40",
}
]
I would like to automatically generate a schema from the collection. Ideally it would not which properties are present in all the documents and mark those as required. Detecting unique columns would also be nice, though not really all that necessary. In any event I would be modifying the schema after it's automatically generated.
I've noticed that there are tools that can do this for JSON. But short of downloading the entire collection as JSON, is it possible to do this using the MongoDb console or a CLI tool directly from the collection?
You could try this tool out. It appears to do exactly what you want.
Extract (and visualize) schema from Mongo database, including foreign
keys. Output is simple json file or html with dagre/d3.js diagram
(depending on command line options).
https://www.npmjs.com/package/extract-mongo-schema

MongoDB - how to properly model relations

Let's assume we have the following collections:
Users
{
"id": MongoId,
"username": "jsloth",
"first_name": "John",
"last_name": "Sloth",
"display_name": "John Sloth"
}
Places
{
"id": MongoId,
"name": "Conference Room",
"description": "Some longer description of this place"
}
Meetings
{
"id": MongoId,
"name": "Very important meeting",
"place": <?>,
"timestamp": "1506493396",
"created_by": <?>
}
Later on, we want to return (e.g. from REST webservice) list of upcoming events like this:
[
{
"id": MongoId(Meetings),
"name": "Very important meeting",
"created_by": {
"id": MongoId(Users),
"display_name": "John Sloth",
},
"place": {
"id": MongoId(Places),
"name": "Conference Room",
}
},
...
]
It's important to return basic information that need to be displayed on the main page in web ui (so no additional calls are needed to render the table). That's why, each entry contains display_name of the user who created it and name of the place. I think that's a pretty common scenario.
Now my question is: how should I store this information in db (question mark values in Metting document)? I see 2 options:
1) Store references to other collections:
place: MongoId(Places)
(+) data is always consistent
(-) additional calls to db have to be made in order to construct the response
2) Denormalize data:
"place": {
"id": MongoId(Places),
"name": "Conference room",
}
(+) no need for additional calls (response can be constructed based on one document)
(-) data must be updated each time related documents are modified
What is the proper way of dealing with such scenario?
If I use option 1), how should I query other documents? Asking about each related document separately seems like an overkill. How about getting last 20 meetings, aggregate the list of related documents and then perform a query like db.users.find({_id: { $in: <id list> }})?
If I go for option 2), how should I keep the data in sync?
Thanks in advance for any advice!
You can keep the DB model you already have and still only do a single query as MongoDB introduced the $lookup aggregation in version 3.2. It is similar to join in RDBMS.
$lookup
Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing. The $lookup stage does an equality match between a field from the input documents with a field from the documents of the “joined” collection.
So instead of storing a reference to other collections, just store the document ID.

GET Values from a custom field via JIRA REST API

I would like to GET all drop down options for a custom field. For system fields, I use the following URI:
http://localhost:8080/rest/api/2/project/XXXX/components
(for components, versons, etc. Basically system fields), so I tried the following for a custom field
http://localhost:8080/rest/api/2/project/XXXX/customfield_10000
and got a 404 error. I'm not sure what I'm doing wrong as I've been googling for the past 19 hours. The best I search result I got was the following documentation: JIRA Developers Documentation
Please assist, I'm not sure What I'm missing
You can get that information either from the createmeta or editmeta REST resources.
Use editmeta if you want to retrieve the available options when editing a specific issue. E.g.
GET /rest/api/2/issue/TEST-123/editmeta
Use createmeta when you want to retrieve the options for a project in combination with an issue type. E.g.
GET /rest/api/2/issue/createmeta?projectKeys=MYPROJ&issuetypeNames=Bug&expand=projects.issuetypes.fields
The customfields with options will be returned like this:
"customfield_12345": {
"schema": {
"type": "string",
"custom": "com.atlassian.jira.plugin.system.customfieldtypes:select",
"customId": 12345
},
"name": "MySelectList",
"allowedValues": [
{
"self": "http://jira.url/rest/api/2/customFieldOption/14387",
"value": "Green",
"id": "14387"
},
{
"self": "http://jira.url/rest/api/2/customFieldOption/14384",
"value": "Blue",
"id": "14384"
}
]
}