title: Flask/SQLAlchemy Insert Into Database
body: <p>Using Flask and SQLAlchemy on my localhost, I am looking to be able to submit a simple contact form and, using AJAX, pass the submitted data along to my Flask API and then insert it into my local database, named <code>contact.db</code>.</p>
  
  <p>To set up my database, I put together a script named <code>setup.py</code>, which successfully creates a database in my working directory. Its contents look as follows:</p>
  
  <pre><code>from sqlalchemy import create_engine, ForeignKey
  from sqlalchemy import Column, Date, Integer, String
  from sqlalchemy.ext.declarative import declarative_base
  from sqlalchemy.orm import relationship, backref
  
  engine = create_engine('sqlite:///contact.db', echo=True)
  Base = declarative_base()
  
  ########################################################################
  class Contact(Base):
      """"""
      __tablename__ = "contact"
  
      id = Column(Integer, primary_key=True)
      f_name = Column(String)
      l_name = Column(String)
      email = Column(String)
      message = Column(String)
  
      #----------------------------------------------------------------------
      def __init__(self, f_name, l_name, email, message):
          """"""
          self.f_name = f_name
          self.l_name = l_name
          self.email = email
          self.message = message
  
  # create tables
  Base.metadata.create_all(engine)
  </code></pre>
  
  <p>My simple contact page collects the data and submits it to my flask route <code>/contact/request</code> using AJAX (I have confirmed this to work via the console). For reference, however, here is the code I use in <code>contact.html</code>:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
    &lt;head&gt;
      &lt;meta charset="utf-8"&gt;
      &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
      &lt;title&gt;Contact&lt;/title&gt;
  
      &lt;!-- Bootstrap --&gt;
      &lt;link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet"&gt;
  
      &lt;!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --&gt;
      &lt;!-- WARNING: Respond.js doesn't work if you view the page via file:// --&gt;
      &lt;!--[if lt IE 9]&gt;
        &lt;script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"&gt;&lt;/script&gt;
        &lt;script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"&gt;&lt;/script&gt;
      &lt;![endif]--&gt;
  
      &lt;!-- jQuery (necessary for Bootstrap's JavaScript plugins) --&gt;
      &lt;script src="https://code.jquery.com/jquery.js"&gt;&lt;/script&gt;
      &lt;!-- Include all compiled plugins (below), or include individual files as needed --&gt;
      &lt;script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"&gt;&lt;/script&gt;
  
  
  
  
  &lt;script&gt;
    $(document).ready(function(){
        $("#submitForm").click(function()
        {
          var firstName = $("#f_name").val();
          var lastName = $("#l_name").val();
          var email = $("#email").val();
          var mess = $("#mess").val();
  
          var nud = {
            "f_name" : firstName,
            "l_name" : lastName,
            "email" : email,
            "message" : mess
          }
  
  
          $.ajax({
            type: "POST",
            url: "/contact/request",
            data: JSON.stringify(nud, null, '\t'),
            contentType: 'application/json;charset=UTF-8',
            success: function(result) {
              console.log(result);
            }
          })
        });
    })
  &lt;/script&gt;
  
  
  
  &lt;/head&gt;
  &lt;body&gt;
  &lt;div class="row"&gt;
    &lt;div class="col-md-3"&gt;&lt;/div&gt;
    &lt;div class="col-md-6"&gt;
      &lt;div class="panel panel-default"&gt;
        &lt;div class="panel-heading"&gt;
          &lt;h1 style="text-align: center"&gt;Contact Me&lt;/h1&gt;
        &lt;/div&gt;
        &lt;div class="panel-body"&gt;
          &lt;form role="form"&gt;
            &lt;div class="form-horizontal" class="form-group" style="width:50%"&gt;
              &lt;label for="name has-success"&gt;First Name&lt;/label&gt;
              &lt;input class="form-control input-md" type="text" class="form-control" id="f_name" placeholder="Matthew"&gt;
            &lt;/div&gt;&lt;br /&gt;
            &lt;div class="form-horizontal" class="form-group" style="width:50%"&gt;
              &lt;label for="email"&gt;Last Name&lt;/label&gt;
              &lt;input class="form-control input-md" type="text" class="form-control" id="l_name" placeholder="Gross"&gt;
            &lt;/div&gt;&lt;br /&gt;
             &lt;div class="form-horizontal" class="form-group" style="width:50%"&gt;
              &lt;label for="email"&gt;Email&lt;/label&gt;
              &lt;input class="form-control input-md" type="email" class="form-control" id="email" placeholder="mattkgross@gmail.com"&gt;
            &lt;/div&gt;&lt;br /&gt;
            &lt;div class="form-group"&gt;
              &lt;label for="aboutMe"&gt;Message&lt;/label&gt;
              &lt;textarea class="form-control" id="mess" placeholder="What's up?" rows="3" &gt;&lt;/textarea&gt;
            &lt;/div&gt;
            &lt;div&gt;
             &lt;button type="button" input type "submit" class="btn btn-success" id="submitForm"&gt;Submit&lt;/button&gt;
            &lt;/div&gt;
          &lt;/form&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="col-md-3"&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Finally, I have my actual Flask API script that I run in order to start up my service on localhost. The <code>/contact</code> route works fine. However, when I send the data via my form submission, I get an internal server error. This is undoubtedly being caused by my incorrect attempt at inserting the parsed JSON into my contact database. Below is the code used in my <code>api.py</code>:</p>
  
  <pre><code>from flask import Flask
  from flask import request
  from flask import render_template
  
  import datetime
  from sqlalchemy import create_engine
  from sqlalchemy.orm import sessionmaker
  from setup import Contact
  
  app = Flask(__name__)
  
  @app.route('/contact')
  def contact():
      return render_template('contact.html')
  
  @app.route('/contact/request', methods=["POST"])
  def contact_request():
      if request.method == "POST":
          engine = create_engine('sqlite:///contact.db', echo=True)
  
          # Create a Session
          Session = sessionmaker(bind=engine)
          session = Session()
  
          new_contact = Contact(request.json['f_name'],
                                request.json['l_name'],
                                request.json['email'],
                                request.json['message'])
  
          # Add the record to the session object
          session.add(new_contact)
          # commit the record the database
          session.commit()
  
          #return str(request.json)
  
  app.debug = True
  app.run()
  </code></pre>
  
  <p>If I comment out the two lines:</p>
  
  <pre><code>session.add(new_contact)
  session.commit()
  </code></pre>
  
  <p>and replace them with <code>return str(request.json)</code>, my console successfully returns the JSON I sent. I am just completely lost as to where I am going wrong in inserting my data into the database and why it is throwing an error at me for my attempt. </p>
  
  <p>Any help you can give me would be very much appreciated - hopefully it's something simple I overlooked in being new to this whole thing. Thanks!</p>