1

I had an issue with that I cann't use my Post request in FastAPI , I used the Post request but the terminal displayed the Get request and I don't know why. And when I used the Body(...) to declare the dict type but it looked didn't work

from fastapi.params import Body
from pydantic import BaseModel

app = FastAPI()
# payload : input parameter of the function
# dict: type of data
#  được truyền vào bằng cách sử dụng FastAPI's Body dependency. ... được sử dụng để chỉ định rằng tham số 
# này là bắt buộc và không thể bỏ qua.
@app.post("/create")
def create_posts(payload: dict = Body(...)):
    # It will extract all the field from the body to the dict
    print(payload)
    return {"message": f"successfully created posts: {payload['title']}"}

@app.get("/")
def get_data():
    return {"message": "Hello World"} 

Here is my error

INFO:     Will watch for changes in these directories: ['T:\\FastAPI']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [14464] using WatchFiles
INFO:     Started server process [3468]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:60812 - "GET /create HTTP/1.1" 405 Method Not Allowed
INFO:     127.0.0.1:60812 - "GET /cart.json HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:60812 - "GET /create HTTP/1.1" 405 Method Not Allowed```
LeThanhDat
  • 19
  • 6
  • 1
    How are you calling your endpoint? It looks like you're sending a GET request to your POST endpoint. – M.O. Apr 19 '23 at 09:51
  • yes, when I use the http://localhost:8000/doc to test the API it works, but I don't understand why I executing a GET request to an endpoint that accepts POST requests although I use the @app.post("/create") – LeThanhDat Apr 19 '23 at 10:19

2 Answers2

2

Problem is your get method is defined at localhost:8000/ (in case you run the app with uvicorn in default mode)

@app.get("/")
def get_data():
    return {"message": "Hello World"}

So you should send a request like

get

Instead of

get2

You should use POST instead

post

Or define something like

@app.get("/create")
def get_data():
    return {"message": "Hello World"}
2

Your code works just fine. Most probably the only issue is that you in fact don't actually send a POST request. Open http://localhost:8000/docs in your browser and try the request yourself.

adam
  • 159
  • 9