stanvooz
stanvooz

Reputation: 542

FastAPI returns "405 Method Not Allowed" error when sending an HTTP request

I have a simple FastAPI endpoint, where I want to receive a string value. In this case, I tried it with a JSON body, but basically it doesn't need to be JSON. I really need only a simple string to separate the requests from each other. Unfortunately, I can't access any of the request parameters with a GET method. I also tried POST method instead, but I get an error:

request:

url = "http://127.0.0.1:5000/ping/"

payload=json.dumps({"key":"test"})
headers = {
"Content-Type": "application/json"
            }
response = requests.request("POST", url, headers=headers, json=payload)

print(response.text)

api:

@app.get("/ping/{key}")
async def get_trigger(key: Request):

    key = key.json()
    test = json.loads(key)
    print(test)
    test2 = await key.json()
    print(key)
    print(test2)


    return 

I can't print anything with post or put:

@app.post("/ping/{key}")
async def get_trigger(key: Request):
...
   or

@app.put("/ping/{key}")
async def get_trigger(key: Request):

I get a 405 Method not allowed error.

How can I get this fixed?

Upvotes: 1

Views: 7290

Answers (1)

Chris
Chris

Reputation: 34045

The 405 Method Not Allowed status code indicates that "the server knows the request method, but the target resource doesn't support this method". You get this error when you attempt, for instance, to send a POST request to a GET route (as shown in your first example).

This, however, is not the only issue with your code (on both client and server sides). Below is given an example on how to achieve what you described in the question using Path parameters. The same could be achieved using Query parameters, as well as Request Body. Please have a look at Python requests documentation on how to specify the parameters/body for each case. I would also highly suggest to take the FastAPI tutorial online—you'll find most of the answers you are looking for there.

app.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/ping/{ping_id}")
async def get_trigger(ping_id: str):
    return {"ping_id": ping_id}

test.py

import requests

url = 'http://127.0.0.1:8000/ping/test1'
resp = requests.get(url=url) 
print(resp.json())

Related answers to 405 Method Not Allowed errors can be found here and here.

Upvotes: 1

Related Questions