Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API Endpoint .htaccess with Optional Fields (PHP)

I am completely new to APIs. I created a UI for our web application (PHP environment) and wanted to develop an API. I used this resource to create an REST API with PHP and this resource for best practices.

So far, I have the API working which would accept endpoints, such as:

  • api/search.json
  • api/search/log.json

The .json is added to meet the criteria of best practices and serves no functionality (other than possibly acting as a separator for my next task). I would like to include some optional fields. I was going to include these after the .json in this format:

  • api/mandatory-term.json?optional=value
  • api/mandatory-term.json?optional=value&anotheroptional=value

This was my attempt at an .htaccess solution:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^api/([^.?]+).json\?(.*)$ api/api.php?request=$1&fields=$2 [QSA,NC,L]
RewriteRule ^api/([^.?]+).json$ api/api.php?request=$1 [QSA,NC,L]
</IfModule>

This is the line that continues to fail:

RewriteRule ^api/([^.?]+).json\?(.*)$ api/api.php?request=$1&fields=$2 [QSA,NC,L]

If I remove the question mark (from the request and .htaccess), I can get the result I want in fields (except for an "&"; that'll break it). Would someone mind helping me understand how to capture that second field after a question mark while including ampersands? I'll most likely use the explode method to separate the capture into an array of optional arguments for the class methods.

Again, I completely new to this. I would love if someone could help me solve my .htaccess problem, but any other advice is welcome. I didn't have the choice of what environment to implement this in. I would have preferred to have done this with J2EE but... no such luck. Thanks!

like image 836
Robert Broden Avatar asked Sep 27 '26 02:09

Robert Broden


1 Answers

I think you were close but you can't match a query string in the pattern of the rewriterule. You need to match the querystring or use QSA. I modified the rules a bit. Give this a try.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteCond %{QUERY_STRING} (.+)
RewriteRule ^api/([^.?]+)\.json$ api/api.php?request=$1&fields=%1 [QSA,NC,L]

RewriteRule ^api/([^.?]+)\.json$ api/api.php?request=$1 [NC,L]
</IfModule>

Note that it will take the entire querystring in the request and add it to the fields var as you requested.

You could just also use the QSA flag to append the query string added to the rewrite.

like image 59
Panama Jack Avatar answered Sep 29 '26 17:09

Panama Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!