Edoardo Piccolotto
Edoardo Piccolotto

Reputation: 21

FastAPI: Error by sending Request Body trough GET

I'm updating some APIs that I have coded using Python and FastAPI. In the actual version I'm sending the info using Query Paramenters, but now I want to try to send the data by using Request Body, but the code doesn't seem to work.

Below you can see a sample of the code on the Server Side where FastAPI should return the text I'm sending (for this example only the "string_to_show" info, but in the real project there would be more fields). I know that is a base code, but this is just a sample.

from fastapi import FastAPI, Path, Query
from pydantic import BaseModel
import uvicorn

app = FastAPI()

class req_body(BaseModel):
    string_to_show:str

@app.get("/test/")
def scraper_shield(payload:req_body):
    request_feedback = str(payload.string_to_show)
    return request_feedback

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

On the Client Side I'm using this code, that simply sends the payload to the server.

import requests

payload = {'string_to_show':'Python is great!'}
r = requests.get('http://127.0.0.1:8000/test/', params=payload)

print(r.text)

When sending the request, I should get the string "Python is Great!" but instead I'm getting some errors, below the Client and Server messages:

Upvotes: 1

Views: 4115

Answers (2)

pkolawa
pkolawa

Reputation: 683

GET methods are not suppose to have body. https://dropbox.tech/developers/limitations-of-the-get-method-in-http

POST method is meant for that. If you really need some robust parametrization with GET (but I really would reconsider that), think about putting them into custom header(s).

Upvotes: 1

Simon Hawe
Simon Hawe

Reputation: 4539

You are sending the parameters as query strings when using r = requests.get('http://127.0.0.1:8000/test/', params=payload). You have to instead use r = requests.get('http://127.0.0.1:8000/test/', json=payload) which will create a request body and send it correctly. This what you also see from the errors, which basically tell you that the required body is missing.

Upvotes: 0

Related Questions