0

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)
zipline86
  • 561
  • 2
  • 7
  • 21
  • purchases is a list. You cannot do `purchases["item"]` because it is not a dictionary – dgan Nov 19 '17 at 16:47

1 Answers1

1
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

dgan
  • 1,349
  • 1
  • 15
  • 28
  • Thanks for helping me out! I've seen the above topics before I wrote my post but I didn't know how to implement those other posts.T hat's why I posted my whole code. I'm no expert and have to start somewhere... – zipline86 Nov 22 '17 at 22:58