DEV Community

Discussion on: Should SQL Query through REST API be a GET or a POST?

Collapse
 
tqbit profile image
tq-bit • Edited

I am curious to understand why you would want to send sql queries over your url. It might expose your API to SQL injection. SQL queries belong into the backend.

For such, you might use stored procedures or query builders. Your API should then be able to take the requested URL query parameters and move them forward to your database model, which in turn uses them for its DB query

Edit: My apologies, I didn't really contribute to your question, did I now?

Assuming you have a separate DB schema / query builder / stored procedure in place, a url with a query could look something like this:

GET: https://server.com/users/?users_trid=orders_trid&users_user_trid=31,32,33&user_status=1

Your controller could then take those params out and forward them to the respective query for the path /users

Collapse
 
niolap profile image
Nicolas Penot

Thank you tq-bit. Actually, we already can get data from table using its path GET: server.com/database/mydb/tables/us....

The idea is to be able to get complex query results in one REST call, thus having SQL to query the data model.

I don't speak about query builder or controller because we have the SQL and REST server process in the database program itself.

You're right, SQL injection are a problem having SQL direct in a GET. In fact, it's just the first step to get the result of queries more elaborated than just GET in the table (as described in my previous comment). Then we're going to have prepared statements feature that you can POST before getting the result through GET + params.

So I think it's more or less corresponding to your feedback. Isn't it?

Collapse
 
tqbit profile image
tq-bit

I think I get your idea now.

I'll be honest, doing REST like this is rather unfamiliar to me. The closest lesson learned I've had on what you name prepared statements is a bound operation or bound function in OData, which exposes a procedure in the form of a URL. Like this, you would ever only have to send a single query + payload, therefor staying true to restful principles.

docs.oasis-open.org/odata/odata/v4...

Now adding OData principles just for the sake of dynamic queries might not be worth it, but perhaps there's a thing or two which might come in handy for you.

Thread Thread
 
niolap profile image
Nicolas Penot

OData principles are in the essence what we should have.
We only need to send SQL to the database server (POST), the database server validates and holds them in a list. Then we call them by their "tag" (GET) with the binding values, e.g. user_id=23&order_id&43...

Also, it will dramatically improve the process to GET data from queries because they're going to be "soft parsed" instead of "hard parsed" at each call.

PS: I didn't know OData, but it's inspiring specifications, thanks tq-bit :)