-1

I made a simple flask API that has two endpoints for me to learn how to use flask. First, there is a GET API that randomly outputs a value from a CSV. I have tested this part and it works fine, but the other part is a POST Endpoint that allows you to upload to the CSV.

I don't have access to my PC right now, so I made all of this from an Android phone using pydroid 3. To test the API, I use https://extendsclass.com/rest-client-online.html, with flask_cors to handle CORS.

When I send the request, it just says "in progress" forever. If I don't use a header saying the content type is application json, it returns 415.

Here is the code:

from flask import Flask
from flask_restful import Resource, Api, reqparse
import pandas as pd
from flask_cors import CORS
import ast
import random
app = Flask(__name__)
CORS(app)
api = Api(app)
    
class Upload(Resource):
        def post(self):
            parser = reqparse.RequestParser()  # initialize
        
            parser.add_argument('text', required=True)
            print(1)
            args = parser.parse_args()  # parse arguments to dictionary
            print(2)
            new_data = pd.DataFrame({
            'id': random.randint(0,1000),
            'text': args['text']
            })
            print(3)
            data = pd.read_csv('words.csv')
            data = data.append(new_data, ignore_index=True)
            print(4)
            data.to_csv('words.csv', index=False)
            return 200

api.add_resource(Upload, '/upload')

I have added print debug statements, although when run, they never appear in console, and the CSV file doesn't get edited.

1 Answers1

0

Much of the code in your question isn't relevant to the problem you're asking about. If we remove it, we get:

from flask import Flask
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)

class Upload(Resource):
        def post(self):
            parser = reqparse.RequestParser()  # initialize

            parser.add_argument('text', required=True)
            args = parser.parse_args()  # parse arguments to dictionary
            return {"text": args.text}


api.add_resource(Upload, '/upload')

Note that in the above code I've fixed the indentation error I pointed out in my comment.

If we have this code in server.py and run it using gunicorn:

gunicorn server:app

Then we can access it like this:

curl -H 'Content-type: application/json' localhost:8000/upload -d '{"text": "hello world"}'

And get the response:

{"text from request": "hello world"}

It looks like everything works as expected.

larsks
  • 277,717
  • 41
  • 399
  • 399