How to Send and Receive Data in Flask
Tags: python, webdev, programming, computerscience
Published: 2022-11-14 08:49:36

**_This article was originally posted on [realpythonproject.com](https://www.realpythonproject.com/how-to-send-and-receive-data-in-flask/)_**

<!-- wp:separator -->
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<!-- /wp:separator -->

<!-- wp:paragraph -->
<p>I’ll be using <a href="https://replit.com/~" rel="noreferrer noopener" target="_blank">Repl.it</a> for writing all the code. Repl.it lets you quickly deploy your API and is really convenient. You can find my <a href="https://replit.com/@rahulbanerjee26/FlaskReceive" rel="noreferrer noopener" target="_blank">Repl here</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here are the 4 types of data we will be looking at</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>Sending/Receiving Parameters</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Sending/Receiving Form Data</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Sending/Receiving JSON String Data</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Sending/Receiving Files</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Why would you want to learn how to Receive/Send Data in&nbsp;Flask?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In a lot of cases when you are developing a Flask API that interacts with 3p services such as other APIs, Webhooks, Serverless Functions, etc, you won’t have control over what kind of data you receive. However, knowing how to receive different kinds of data in Flask will help you handle the data appropriately. If the 3p service’s source code is in Python, you can go over this article to find the relevant section. Being able to send different formats of data is also helpful since it’ll allow you to write unit tests for your API.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Project Setup</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Install Flask using the following command</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="bash" class="language-bash">pip3 install flask</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Below is a simple Flask API</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">from flask import Flask,request
app = Flask('app')

@app.route('/')
def hello_world():
  return 'Hello, World!'


app.run(host='0.0.0.0', port=8080)</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The endpoint simply returns a string.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Parameters</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>How to Access Parameters from a Request in&nbsp;Flask</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Below is a code snippet that can access the parameters that were sent.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">@app.route('/receiveParameters')
def receiveParameters():
  data = request.args
  return {'data': data}, 200</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>You can use the <code>request.args</code>to access the parameters. It returns the parameters as a dictionary.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>How to Make a Request with Parameters Using&nbsp;Python</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Below is the code snippet which makes a request to a URL and sends a couple of parameters.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">import requests

url = 'https://FlaskReceive.rahulbanerjee26.repl.co'

response = requests.get(url+'/receiveParameters?name=Rahul&amp;age=22')
print(response.json())


response = requests.get(url+'/receiveParameters',
params = {
  'name': 'Rahul',
  'age': 22
  }
)
print(response.json())

'''
OUTPUT
{'data': {'age': '22', 'name': 'Rahul'}}
{'data': {'age': '22', 'name': 'Rahul'}}
'''
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>There are two ways you can pass parameters, the first is to directly add it to the URL and the second is to add it in a JSON object.</p>
<!-- /wp:paragraph -->

<!-- wp:separator -->
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<!-- /wp:separator -->

<!-- wp:heading {"level":3} -->
<h3>Form Data</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>How to Receive Form Data in&nbsp;Flask</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Flask has a property called <code>request.form</code> that lets it access form data. Below is an endpoint to receive form data</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">@app.route('/receiveFormData',methods=['POST'])
def receiveFormData():
  name = request.form['name']
  age = request.form['age']
  print(name)
  print(age)
  return{
    'data': {
      'name': name,
      'age': age
    }
  },200</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>It will accept <code>POST</code> requests and simply return the data.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We will look at two ways to send form data to the above endpoint. In the first way, we will create a simple form in HTML, and in the second way, we will send the form data using Python</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>How to send For Data using HTML to our Flask API&nbsp;Endpoint</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I created a new repl for this. You can find it over <a href="https://replit.com/@rahulbanerjee26/LumpyGlamorousPreprocessor" rel="noreferrer noopener" target="_blank">here</a>. Below is the HTML form.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">&lt;!DOCTYPE html>
&lt;html>
&lt;body>

&lt;h2>HTML Forms&lt;/h2>

&lt;form action="https://FlaskReceive.rahulbanerjee26.repl.co/receiveFormData" method='post'>
  
  &lt;label for="name">First name:&lt;/label>&lt;br>
  &lt;input type="text" name='name'>&lt;br>
  
  &lt;label for="age">Last name:&lt;/label>&lt;br>
  &lt;input type="text" name='age'>&lt;br>&lt;br>
  
  &lt;input type="submit" value="Submit">
&lt;/form> 

&lt;/body>
&lt;/html></code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>For the <code>action</code> attribute, I set the value to the Flask Endpoint we created in the above section. We also set <code>method</code> to <code>POST</code> since the endpoint only accepts Post Requests.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This will create a form with two inputs and submit button. Whenever the user clicks on the submit button, the form will make a Post request to the <code>receiveFormData</code> endpoint.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>How to Send Form Data using&nbsp;Python</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This could be useful when you are writing unit tests to test your Flask API.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Below is a code snippet to test <code>request.form</code>&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">data = {
  'name': 'Rahul',
  'age': 22
}
print("Request to /receiveFormData")
formResponse = requests.post(
  url+'/receiveFormData',
  data=data,
  headers= {
    'Content-Type': 'application/x-www-form-urlencoded'
  })
print(formResponse.json())</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The <code>Content-Type</code> is set to <code>application/x-www-form-urlencoded</code>&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:separator -->
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<!-- /wp:separator -->

<!-- wp:heading {"level":3} -->
<h3>JSON StringData</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>JSON is something that is common to most programming languages so this might be the most common case.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>How to Receive JSON String Data in&nbsp;Flask</h4>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">from flask import jsonify

@app.route('/receiveJson',methods=['POST'])
def receivePostData():
  data = jsonify(request.json)
  print(data)
  return  data,200</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We can use <code>request.json</code> to retrieve the data. To convert the json string object to JSON&nbsp;, we will use a Flask method called <code>jsonify</code>&nbsp;. This will let you access keys similar to how you would do with a dictionary.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>How to Send JSON String Data using&nbsp;Python</h4>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">import json

print("Request to /receiveJson")
jsonData={
  'name': 'Rahul',
  'age': 22
}
jsonResponse = requests.post(
  url+'/receiveJson',
  json=json.dumps(jsonData)
)
print(jsonResponse.json())</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We will use <code>json.dumps</code> to convert the dictionary to a JSON String before attaching it as a payload to the POST request.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can directly send the dictionary without converting it into a JSON string as well. In this case, you wouldn’t need to use <code>jsonify</code> it before returning the response.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:separator -->
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<!-- /wp:separator -->

<!-- wp:heading {"level":3} -->
<h3>Files</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I have created a <a href="https://replit.com/@rahulbanerjee26/FlaskReceive#testFile.txt" rel="noreferrer noopener" target="_blank">simple text file</a>. We will attach the text file as a payload to the API endpoint. The API will read the contents of the file and return the content.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>How to Receive Files in&nbsp;Flask</h4>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">@app.route('/receiveFile',methods=['POST'])
def receiveFile():
  file= request.files['textFile']
  data = file.read().decode('utf-8')
  print(data)
  return {
    "data": data
  },200</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p><code>request.files</code> returns an <code>FileStorage</code> object, as a result, you can directly use <code>read</code> to get the content of the file. We will need to decode it before sending it as response data.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Working with files can get somewhat confusing, specifically the following line</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">data = file.read().decode('utf-8')</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Depending on the format of the file, you might not have to decode it. Instead, you might have to use something like <code>json.loads(byteData)</code> to convert a byte object to JSON.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>How to Send Files Using&nbsp;Python</h4>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="python" class="language-python">print("Request to /receiveFile ")
with open('testFile.txt','r') as f:
  fileResponse = requests.post(
    url+'/receiveFile',
    files={
      'textFile': f 
    }
  )
print(fileResponse.json())</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Depending on if you open it using mode <code>r</code> or <code>rb</code>&nbsp;, the code you wrote to create the endpoint will change.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Conclusion</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this article, we created 4 endpoints for our API. Each endpoint expected a different format of data. I hope you found this article useful.  If you liked this article, you might like another article that <a href="https://www.realpythonproject.com/how-to-authenticate-using-keys-basicauth-oauth-in-python/" target="_blank" rel="noreferrer noopener">helps you get comfortable working with APIs</a></p>
<!-- /wp:paragraph -->