Search code examples
pythonflaskhttp-headers

Flask REST api headers returned upon request and what exactly is a header


What exactly is a REST header? I'm having problems understanding what a header is because at first I thought read that it's something that the requester doesn't see in the HTTP. But then when I do some more research I see them sometimes going in the body. Can somebody please help me understand it with a general understanding?

Also, I have homework for trying to develop a Flask API that returns data and a header like "v:1.2" in all requests made. I have some questions that I am having problems figuring out.

  1. How do I get my API to return a header that contains custom information such as "XYZ" every time a request is made? Will this get returned in the body?

  2. I made a "/" home request that returns all the data from my JSON and then I tried making a "/item" that return data from the "items" of my JSON but I can't get it to work. It always returns that it can't be found when I test the API. Is the problem when I write purchases["item"]?

data

 purchases = [
 {
"transactions": [
    {
        "items": [
            {
                "name": "My Item:",
                "price": 15.99
            }
        ],
        "name": "My Wonderful Store"
    },
    {
        "time": [
            {
                "hour bought": "02:00"
            },
        ]
    }
]
}
]

views

# GET /
@app.route("/")  # shows your whole list
def get_purchases():
    return jsonify({"purchases": purchases})


# GET /item
@app.route("/item")  # gets just item
def get_statistics_loads():
     return jsonify({"items:": purchases["items"]})

app.run(port=5000)

Solution

  • import flask
    from flask import  jsonify
    from flask import make_response
    
    app = flask.Flask(__name__)
    purchases = [
        {
            "transactions": [
                {
                    "items": [
                        {
                            "name": "My Item:",
                            "price": 15.99
                        }
                    ],
                    "name": "My Wonderful Store"
                },
                {
                    "time": [
                        {
                            "hour bought": "02:00"
                        },
                    ]
                }
            ]
        }
    ]
    
    
    # GET /
    @app.route("/")  # shows your whole list
    def get_purchases():
        response = make_response(jsonify(purchases))
        response.headers["customHeader"] = "custom value"
        return response
    

    Your purchases is a list, not a dict. You cannot access "item" in a dict-way