Filter nested array in Resource API Link

Hey guys.

I’m trying to filter a nested array in a url. Array example:

{
  - data: {
       name: "blablabla",
       idx: 0,
     - drug: [
        - {
              name: "xxxxxx",
              drug_code: "drugcode",
              drug_name: "drugname",
              dosage: "drugdosage",
              period: "drugperiod",
          }
       ]
    }
}

URL:

https://xxxx.frappe.cloud/api/resource/Drugs?filters=[["idx","=","0"]]

Now that’s the way I filter on the data in the “data”-array. But how would I go about filtering on the data inside the nested array “drug”?

I’ve tried this and many other methods, but nothing is working:

https://xxxx.frappe.cloud/api/resource/Drugs?filters=[["drug"],["drug_name","=","drugname"]]

If I try this:

https://xxxx.frappe.cloud/api/resource/Drugs?filters=[["drug_name","=","drugname"]]

I get this error:

frappe.exceptions.DataError: Field not permitted in query: drug_name

Is what I’m trying to do at all even possible? Any ideas? If it’s not possible please let me know so I can stop wasting my time trying to figure this out. Thank you!

Welcome!

What you’re calling a “nested array” is more often called a child doc in Frappe lingo. You can filter by child doctypes by sending a four value array, something like:

filters=[['Drug', 'drug_name', '=', 'Paracetamol']]
(Child Doctype Name, Child field, operator, value)

I’m a bit confused about what you’re presenting here, though. What is the parent doctype of “blablabla”, and what is the child doctype with the values like “dosage”, “period”, etc.? For what I’ve described here, you want to poll the Parent Doctype rest endpoint but then filter by the child. The four part array should let you do that.

Hi Peter.

Sorry for the presentation, but what you suggested worked. Thanks alot!

Nothing to apologize for, but I was worried you were also maybe polling the wrong endpoint. If it’s working, that’s proof you’re not! Glad it’s working. I’ll update the documentation to make this clearer.

3 Likes

No it’s the correct one. Thanks alot! I have another question if you might be able to help me. Is there a way to group the results based on the filters in the link? Like adding Group by “drug_name” in the link? So if there’s several results with the same drug I just want one of them to show. Thank you very much!

Good question. You might be able to get sorting based on child documents to work, but I don’t think you can do anything more complicated than that. REST APIs are meant to be pretty simple.

If you’re looking to do a bit more processing, you might consider writing a python method and then calling it via RPC. The easiest way to do this probably is via Server Scripts. With that, you’ll have a much broader array of possibilities available to you, and the results can be returned however you prefer.

https://frappeframework.com/docs/v13/user/en/desk/scripting/server-script#23-api-scripts

1 Like

Ok I will try! Thanks alot!