Python: POST request with an extended GET request in Fast API

Athar Naveed
9 min readAug 11, 2024

--

Assalam o Alaikum and Hello there!

Roman Urdu
For reading in English, scroll to the bottom.

Aaj hum Fast API mein GET aur POST request ko zara ghor 🧐 sy dekhein gy, last blog mein humny Fast API ko set up krky aik simple GET request ki thi.

GET and POST request mein 2 cheezein aur ati hain:

  1. Dynamic Paths.
  2. Params

Dynamic Paths

Dynamic Paths ko easily samjhany ky lye, hum linkedin ki example lety hain, is picture mein dekhein:

LinkedIn profile page

Jb bhi aap Linkedin mein “View Profile” pr click krein gy tou apky pass ye path aye ga, “www.linkedin.com/in” joky sb ky lye same rhy ga, “/in/” ky baad aap jo bhi name add krein gy wo dynamic hoga aur usi ky mutabik website backend sy data fetch krky laye gi.

Chalein isko Fast API mein dekhty hain:

# Dynamic Path
@app.get("/in/{name}")
def request(name:str)->dict:
return {"name":name}

Ab is code ko line by line smjhty hain:

  • @app.get(): Ye aik decorator hai, jismein ‘/in/’ ki jagah pr aap jo add krna chahein kr skty hain, usky baad apko agar koi specific person/data ko access krna hai, tou curly braces ky ander koi bhi var name add kr dein.
  • def request(): Ye aik method hai, is method ka name aap kuch bhi rkh sakty hain, isky ander apko wohi var ka name pass krna hai, jo apny decorator ky path mein pass kya tha.
    Aur ye method aik dict format mein us name ko return kr rha hai, jo aap ny pass kya hai.
The output of the above-executed code

Ismein 3 cheezein dekhny wali hain:

  1. Input: Jahan pr meiny apna name enter kya hai.
  2. Request URL: Ap dekh skty hain ky, ‘/in/’ as it is aya hai likin usky baad jo name meiny enter kya tha, wo URL mein aya hai.
  3. Response Body: Ismein jo data humny enter kya tha wo as it is returned ho gaya hai, dict format mein.

Next hai humaray pass

Params

Isko bhi aik example sy smjhata hun, let’s say aap aik laptop ki website pr jatay hain, aur laptops search krty hain.

Example website

Yahan pr bhi 3 cheezein hain, jo aap ko ghor sy dekhni hain:

  1. URL
  2. Left side bar (Jismein Color, Graphic Series waghera likha hai)
  3. Main Content (Used Laptops wala area)

Ab aap left side bar sy jesy hi koi option select krty hain like, Generation

Clicked Generation from Left side bar

Ab URL pr ghor krein, jesy hi generation pr click hua tou, URL ky path mein “?” aya aur usky baad “laptop_generation=9577”.

?: Batata hai ky ab params start hony lagay hain.

laptop_generation: Aik var hai, iski jagah aap koi bhi name dy skty hain.

9577: Us var ki value hai, similarly yahan pr bhi aap jo add krna chahein add kr skty hain. Mostly yahan pr information add hoti hai, jisko hum use krty hain.

Ab let’s say apko multiple params pass krny hain like, Laptop ki Generation: 10th ho aur usmein
Graphic Series: Intel UHD ho tou aisy mein apky pass URL kuch is tarah ka hoga:

Output for multiple params

URL pr ghor krein gy tou aap ko maloom hoga ky, ab beech mein aik “&” agaya hai, joky 2 params ko link kr rha hai, Aur content mein sirf wo laptops display ho rhy hain, joky 10th Gen ky hain aur jin mein Intel UHD ka Graphic Card laga hai.

Ye cheez sorting ky lye bhi use hoti hai like, “Price: Low-High — High-Low”.

Ab isko Fast API mein implement krty hain.

# Params
@app.get("/in")
def request(name:str)->dict:
return {"name":name}

Is case mein apka pura code same rhy ga, sirf dynamic path jismein humny curly braces add krky, var add kya tha wo remove ho jaye ga.
Humaray pass output kuch aisy aye gi:

Output of above executed code

Is baar meiny name mein, “intel” pass kya hai, means mein intel processor ky laptops ko filter out krna chah rha hun.
Is case mein agar aap Request URL ko check krein gy tou is baar, ‘/in’ ky baad “intel” nhi arha blky, “?name=intel” arha hai, yani ky param.
Jismein:
“name”: aik variable hai, yani aap iski jagah pr kuch aur bhi add krskty hain, aur jb aap ny value ko access krna hai, tou bhi yehi var ka name pass krna hai.
Just like in Response Body.
“intel”: intel aap ky pass koi bhi value/data ho skta hai jisko aap ny fetch krna hai.

POST request

Same kaam hum POST request ky through bhi kr skty hain.
But POST aur GET request mein difference kya hai?

## GET
Jb bhi hum GET request ky through data pass krty hain, tou
wo data humaray pass URL mein bhi show hota hai.

## POST
Likin jb hum POST request use krty hain, as a method tou URL
mein data display nhi hota. Ye method specifically user registeration
forms mein use hota hai

Isi liye agar aap browser mein POST request try krein gy, tou wo aap ko ye error show kry ga:

"detail": "Method Not Allowed"

Because by default browsers, GET request krty hain, POST request nhi.

Same methods:

  1. Dynamic Paths
  2. Params

POST method ky sath apply krein gy, result same rhy ga, the difference is URL mein data show nhi hoga.

Dynamic Paths

@app.post("/in/{name}")
def request(name:str):
return {"name":"Hello there! "+name}

Output apky pass kuch aisi aye gi:

Output of the above executed code

Yahan request URL mein data anay ka matlab hr giz ye nhi hai ky, jb aap isko production mein ly kr jayein gy tou wahan bhi apko data display hoga.

Params

@app.post("/in")
def request(name:str):
return {"name":"Hello there! "+name}

Iski apkay pass output kuch aisi aye gi:

The output of the above-executed code

That’s it!

Aglay blog mein miltay hain, Python aur TypeScript mein kuch zabardast krty hain.

English

Today we are going to take a deep dive in Fast API’s GET & POST request, In the last blog, we have set up the Fast API & made a simple GET request.

There are 2 things that extends the GET & POST request:

  1. Dynamic Paths
  2. Params

Dynamic Paths

To easily understand the Dynamic Paths, let’s look at this example of the LinkedIn:

LinkedIn Profile URL

Whenever you are going to open the LinkedIn, you’ll see this sort of URL, “www.linkedin.com/in/” this remains same for everyone, after “/in/” there will be a dynamic path/name that’ll tell the backend to fetch that specific data from the database.

Let’s look at it through Fast API code:

# Dynamic Path
@app.get("/in/{name}")
def request(name:str)->dict:
return {"name":name}

Now let’s understand this code line by line.

  1. @app.get(): It is a decorator that is making a GET request, the path inside it, “/in/” will be whatever you want to add, and will be as it is whenever we’ll fetch data from this path.
    The var name inside the curly braces is also a variable means you can give it, whatever name you want. And when you’ll hit this path, you have to pass some name at this place.
    Like that in the LinkedIn case, where my name appears after “/in/”. This will be your name in your case.
  2. def request(): Again function name can be whatever you want. This function will be called as soon as we hit this path, and the param should be the same as the var inside the curly braces.
    This method is returning the name that we have received in the URL, in the dict format or in this case JSON format.
The output of the above executed code

There are 3 things to focus on:

  1. Input: The place where I have entered my name, is the place where you can enter dynamic data.
  2. Request URL: You can see that, “/in/” has appeared as it is but, after that there is my name.
  3. Response Body: And that name is returned as it is in the dict format.

Next we have is Params.

Params

Let’s understand this with an example as well, you visit a laptop website to buy a laptop.

Example Website

Now there are 3 things you need to focus 🧐on:

  1. URL
  2. Left Bar (where color, graphic series etc… is written)
  3. Main Content (Used laptops area)

Now as soon as I click on the Generation and choose one from it

The URL is to be observed

🧐Focus on the URL, the URL has changed and this time a “?laptop_generation=9577” appears.
Let me tell you what this all means.

“?”: It tells that params are coming.
“laptop_generation”: It is a var, and you can give it any name.
“9577”: It is a value of that var and tells the website to load the 10th Gen laptops. It’s up to you how you handle it.

Now if you want to pass multiple params to it, how the URL would appear? Let’s say we are looking for a 10th gen laptop with Intel UHD graphic card.
Then the URL would be like this:

The output URL with multiple params

Now, if you see the URL there are 2 params, joined with an ‘&’. And in the contents, only those laptops are being shown, that have Intel UHD graphic cards and are of the 10th gen.

This thing is also used for sorting Prices: Low-High or High-Low.

Now let’s see this in Fast API.

# Params
@app.get("/in")
def request(name:str)->dict:
return {"name":name}

Now in this case, your whole code remains the same except for the Dynamic path that is removed. Rest is the same.

Let’s see its output:

The output/example of the above-executed code

Again focus on these 3 things:

  1. Input
  2. Request URL
  3. Response Body

The input contains the name intel, as we are looking for intel graphic cards.
You can see in the request URL, this time, instead of a “/”, there appears to be a “?name=intel”, and we know what this all means.
And the value of the name var is returned as it is.

“name”: It is the var, used to access the value while sorting or fetching the resource based on the use case.

Now let’s see, how it is with POST request.

POST request

We can do the same thing in POST request as well but, what is the difference in both?


## GET request
It is mostly used to fetch data from the database, and all the
requested data can be seen in the URL.

## POST request
It is used to send data to the backend for storing it in the
database. And the data sent through this method is not visible
in the URL. That's why it is mostly used in user registeration
forms.

And for the same reason, if you’ll try to make a POST request through the browser like we did for the GET request, you’ll get this error:

"detail": "Method Not Allowed"

Because by default browsers make a GET request.

Let’s see the 2 methods for POST request:

  1. Dynamic Paths
  2. Params

Dynamic Paths

@app.post("/in/{name}")
def request(name:str):
return {"name":"Hello there! "+name}

The output will be something like this:

The output of the above executed code

The data appeared in the URL, just because we are testing it. It doesn’t mean that it’ll be the same, when we’ll use it in the production.

Params

@app.post("/in")
def request(name:str):
return {"name":"Hello there! "+name}

Its output would be like this:

The output of the above code

That’s it!

See you in the next blog with some more exciting work on TypeScript & Python.

--

--

Athar Naveed
Athar Naveed

Written by Athar Naveed

Carving a path for junior devs so that they can easily navigate through the hurdles that made my learning experience challenging. Also loves Gardening!

No responses yet