In AstroJS (I'm new) I'm able to retrieve my full Strapi table data using these lines of code:
const response = await fetch("http://127.0.0.1:1337/api/teams?populate=*");
const { data } = await response.json();
Or using the Filters option to get a specific result eg
http://127.0.0.1:1337/api/teams?filters[name][$contains]=john;
const { data } = await response.json();
Both above is placed in JSON data.
I would like to use the finOne function that Strapi has in their documentation.
const entry = await strapi.db.query('api::blog.article').findOne({
select: ['title', 'description'],
where: { title: 'Hello World' },
populate: { category: true },
});
const entry = await strapi.db.query('http://127.0.0.1:1337/api/teams').findOne({
select: ['title', 'name'],
where: { name: 'john' },
populate: { category: true },
});
Here is a simple of a simple implementation.
My collection type
Create a custom route.
module.exports = {
routes: [
{ // Path defined with an URL parameter
method: 'GET',
path: '/custom-query',
handler: 'item.customQuery',
}
]
}
Create custom controller
"use strict";
/**
* item controller
*/
const { createCoreController } = require("@strapi/strapi").factories;
module.exports = createCoreController("api::item.item", ({ strapi }) => ({
async customQuery(ctx) {
const entry = await strapi.db.query('api::item.item').findOne();
return entry;
},
}));
Then make the following request
{
select: ['name', 'description', 'quantity'],
where: { name: 'item 1' },
}
My response:
query: http://localhost:1337/api/custom-query?select[0]=name&select1=description&select2=quantity&where[name]=item 1
You can use the query builder here https://docs.strapi.io/dev-docs/api/rest/interactive-query-builder
Here is the repo project: https://github.com/paulnotfromstrapi/strpai-custom-controller-route/tree/main/src/api/item
Hope this helps, but you can accomplish the same thing just by calling the find method and passing appropriate filtering params.
No need to write custom code.
For the same example.
Instead of using the custom route I created, I am just going to use the find method that exists out of the box.
Now I am going to pass this query.
{
filters: {
name: "item 1",
},
fields: ['name', 'description', 'quantity'],
}
query: http://localhost:1337/api/items?filters[name]=item 1&fields[0]=name&fields1=description&fields2=quantity
Here is my response.
Notice the additional benefits of returning pagination. This is not something you get with db.query
and will have to implement yourself.
So if you need to have ability to filter just use the find
endpoint.
That would be my recommendation over the custom route with db.query that I showed.