title: Flask API MySQL queries
body: <p>I'm playing around with an inventory database and trying to make a REST api with flask.</p>
  <p>I want to be able to hit a url like <a href="http://myapp.com/products" rel="nofollow noreferrer">http://myapp.com/products</a>, which returns JSON of <em>all</em> the products in the database. I also want to have an optional parameter of a product id like <a href="http://myapp.com/products/%7Bid%7D" rel="nofollow noreferrer">http://myapp.com/products/{id}</a> and return the product matching the id passed to it. Fairly standard stuff.</p>
  <p>My question is about the best way to generate the sql query string based on whether the user passes an id to the url or not.</p>
  <p>The quick and dirty I have is:</p>
  <pre><code># Products
  @app.route('/products/&lt;int:id&gt;/', methods=['GET', 'POST'])
  @app.route('/products', defaults={'id' : 0}, methods=['GET', 'POST'])
  def products(id):
      products = []
      if(id != 0):
          cur.execute(&quot;&quot;&quot;SELECT stuff
          FROM products
          WHERE products.id = %s&quot;&quot;&quot;, (id,))
      else:
          cur.execute(&quot;&quot;&quot;SELECT stuff
          FROM products&quot;&quot;&quot;)
  </code></pre>
  <p>This works but just feels wrong, especially when my &quot;stuff&quot; query is a big long query and repeated twice for each condition, minus the WHERE id = %.</p>
  <p>What's the better way to generate these queries based on whether the user passes an id to the url?</p>