title: Connect and query from a BigQuery database via a Google Cloud Function (Python)
body: <p>I have</p>
  <ol>
  <li>A google Cloud Function (main.py + requirements.txt)</li>
  <li>A bigQuery Database</li>
  <li>Working query</li>
  </ol>
  <p>Can someone help me with a link/tutorial/code to connect to this bigquery database using my Google Cloud Function in Python and simply query some data from the database and display it.</p>
  <p>I tried the <a href="https://cloud.google.com/bigquery/docs/reference/libraries" rel="noreferrer">https://cloud.google.com/bigquery/docs/reference/libraries</a> but it was related to connecting to big query from a normal deployment and not a Google Cloud Function.</p>
  <p>This is what I have so far. It is deploying without an error, but upon testing, it is giving a 500 error</p>
  <p>main.py (sample public query</p>
  <pre><code>from google.cloud import bigquery
  
  def query_stackoverflow(request):
   client = bigquery.Client()
   query_job = client.query(
      &quot;&quot;&quot;
      SELECT
        CONCAT(
          'https://stackoverflow.com/questions/',
          CAST(id as STRING)) as url,
        view_count
      FROM `bigquery-public-data.stackoverflow.posts_questions`
      WHERE tags like '%google-bigquery%'
      ORDER BY view_count DESC
      LIMIT 10&quot;&quot;&quot;
  )
  
  results = query_job.result()  # Waits for job to complete.
  return Response(&quot;{'message':'successfully connected'}&quot;, status=200, mimetype='application/json')
  </code></pre>
  <p>requirements.txt</p>
  <pre><code>google-cloud-bigquery
  </code></pre>
  <p>Error log:</p>
  <pre><code>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 3.2 Final//EN&quot;&gt;
  &lt;title&gt;500 Internal Server Error&lt;/title&gt;
  &lt;h1&gt;Internal Server Error&lt;/h1&gt;
  &lt;p&gt;The server encountered an internal error and was unable to complete your 
  request. Either the server is overloaded or there is an error in the 
  application.&lt;/p&gt;
  </code></pre>