DEV Community

Cover image for How to Send and Receive Data in Flask
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realpythonproject.com

How to Send and Receive Data in Flask

This article was originally posted on realpythonproject.com


I’ll be using Repl.it for writing all the code. Repl.it lets you quickly deploy your API and is really convenient. You can find my Repl here

Here are the 4 types of data we will be looking at

  • Sending/Receiving Parameters
  • Sending/Receiving Form Data
  • Sending/Receiving JSON String Data
  • Sending/Receiving Files

Why would you want to learn how to Receive/Send Data in Flask?

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.

Project Setup

Install Flask using the following command

pip3 install flask

Below is a simple Flask API

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)

The endpoint simply returns a string.

Parameters

How to Access Parameters from a Request in Flask

Below is a code snippet that can access the parameters that were sent.

@app.route('/receiveParameters')
def receiveParameters():
  data = request.args
  return {'data': data}, 200

You can use the request.argsto access the parameters. It returns the parameters as a dictionary.

How to Make a Request with Parameters Using Python

Below is the code snippet which makes a request to a URL and sends a couple of parameters.

import requests

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

response = requests.get(url+'/receiveParameters?name=Rahul&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'}}
'''

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.


Form Data

How to Receive Form Data in Flask

Flask has a property called request.form that lets it access form data. Below is an endpoint to receive form data

@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

It will accept POST requests and simply return the data.

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

How to send For Data using HTML to our Flask API Endpoint

I created a new repl for this. You can find it over here. Below is the HTML form.

<!DOCTYPE html>
<html>
<body>

<h2>HTML Forms</h2>

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

</body>
</html>

For the action attribute, I set the value to the Flask Endpoint we created in the above section. We also set method to POST since the endpoint only accepts Post Requests.

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 receiveFormData endpoint.

How to Send Form Data using Python

This could be useful when you are writing unit tests to test your Flask API.

Below is a code snippet to test request.form 

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())

The Content-Type is set to application/x-www-form-urlencoded 


JSON StringData

JSON is something that is common to most programming languages so this might be the most common case.

How to Receive JSON String Data in Flask

from flask import jsonify

@app.route('/receiveJson',methods=['POST'])
def receivePostData():
  data = jsonify(request.json)
  print(data)
  return  data,200

We can use request.json to retrieve the data. To convert the json string object to JSON , we will use a Flask method called jsonify . This will let you access keys similar to how you would do with a dictionary.

How to Send JSON String Data using Python

import json

print("Request to /receiveJson")
jsonData={
  'name': 'Rahul',
  'age': 22
}
jsonResponse = requests.post(
  url+'/receiveJson',
  json=json.dumps(jsonData)
)
print(jsonResponse.json())

We will use json.dumps to convert the dictionary to a JSON String before attaching it as a payload to the POST request.

You can directly send the dictionary without converting it into a JSON string as well. In this case, you wouldn’t need to use jsonify it before returning the response. 


Files

I have created a simple text file. 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.

How to Receive Files in Flask

@app.route('/receiveFile',methods=['POST'])
def receiveFile():
  file= request.files['textFile']
  data = file.read().decode('utf-8')
  print(data)
  return {
    "data": data
  },200

request.files returns an FileStorage object, as a result, you can directly use read to get the content of the file. We will need to decode it before sending it as response data.

Working with files can get somewhat confusing, specifically the following line

data = file.read().decode('utf-8')

Depending on the format of the file, you might not have to decode it. Instead, you might have to use something like json.loads(byteData) to convert a byte object to JSON.

How to Send Files Using Python

print("Request to /receiveFile ")
with open('testFile.txt','r') as f:
  fileResponse = requests.post(
    url+'/receiveFile',
    files={
      'textFile': f 
    }
  )
print(fileResponse.json())

Depending on if you open it using mode r or rb , the code you wrote to create the endpoint will change.

Conclusion

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 helps you get comfortable working with APIs

Top comments (0)