Posted by: Zeeshan Amjad | October 31, 2023

Values passing in HTTP call


In HTTP request, parameter can be passed in more than one way. For GET request, we can pass value by either query parameter, path parameter or header. For POST or PUT we can even pass it in the body. Let’s focus on the GET request and see how can we pass values in different ways.

We already saw the example of query passing here https://zamjad.wordpress.com/2023/09/01/writing-webservice-with-python/

Here we are going to write a simple program using Flask to show how to retrieve values passing using query, path and header.

from flask import Flask, request, jsonify
app = Flask(__name__)
 
@app.route("/")
def hello() -> str:
    return jsonify("Hello World from Python")

@app.route("/query")
def queryParam() -> str:
    value1 = request.args.get("key1")
    value2 = request.args.get("key2")
    return jsonify({
        "key1": value1,
        "key2": value2
    })
 
@app.route("/path/<parammeter>")
def pathParam(parammeter) -> str:
    value = request.view_args["parammeter"]
    return jsonify({"parameter": value})

@app.route("/header")
def headerParam() -> str:
    value = None
    if "parameter" in request.headers:
        value = request.headers["parameter"]
    return jsonify({"parameter": value})

if __name__ == "__main__":
    app.run()
    

The first one is very simple, we pass the values in the form of key value pair in the URL, here is one such example.

localhost:5000/query?key1=hello&key2=world

Its output would be something like this.

{

     "key1": "hello",

    "key2": "world"

}

To pass the value in the form of path we would call it something like this

localhost:5000/path/pathvalue

Here is the output of this

{

    "parameter": "pathvalue"

}

The third way is to pass value via header. The simplest way to pass this using Postman or similar tool. We can set the key value in the header and pass it. Here is the output of the program when set key is “parameter” and “value” as a value.

{

"parameter": "value"

}

If we call it from browser, then its value would be null.


Leave a comment

Categories