How to Create POST Endpoints in FastAPI

If you want people or other apps to send new data to your API, you need a POST endpoint. It should also reject bad data before it’s saved.

In this tutorial, we’ll create POST endpoints in FastAPI: a Pydantic model describes the JSON body, @app.post() receives it, and the response comes back as 201 Created.

Here’s what we’re building, a real request sent from the docs page:

Swagger UI showing a FastAPI POST /jobs request returning 201 Created with the new job as JSON
The finished endpoint: 201 Created, a new ID and no private recruiter email.

Before You Start

You’ll need FastAPI installed, so set up FastAPI and your first API if you haven’t. I ran everything here on Python 3.12.5 and FastAPI 0.162.2, and the test scripts use httpx, which ships with fastapi[standard].

Our running sample is one job posting:

FieldTypeSampleRequired
titlestrData AnalystYes
citystrAustinYes
salaryfloat92500.00Yes
posted_ondate2026-12-10Yes
remotebooltrueNo, defaults to false
recruiter_emailstrdana.reyes@example.comYes, but private

Step 1: Create a POST endpoint with a Pydantic model

A POST request carries its data in the body, so we’ll describe that body first.

  1. Create a folder with an empty main.py.
  2. Paste in the code below.
  3. Run fastapi dev main.py in a terminal (the Uvicorn guide covers the other ways to start it).
from datetime import date

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class JobIn(BaseModel):
    title: str
    city: str
    salary: float
    posted_on: date
    remote: bool = False
    recruiter_email: str


@app.post("/jobs")
def create_job(job: JobIn):
    return job
VS Code showing a FastAPI main.py with a Pydantic JobIn model and POST route, with the fastapi dev server running on port 8000
The server reloads every time you save the file.

FastAPI treats the parameter as the JSON body because its type is a Pydantic model. Single values like int or str become query parameters instead.

Checkpoint: The terminal shows the server running at http://127.0.0.1:8000.

Step 2: Send a JSON request to the POST endpoint

A browser’s address bar only sends GET requests, so we need a small script. Keep the server running and save this as post_job.py. And the FastAPI beginner tutorial explains how requests reach routes.

import json
import httpx

job = {
    "title": "Data Analyst",
    "city": "Austin",
    "salary": 92500.00,
    "posted_on": "2026-12-10",
    "remote": True,
    "recruiter_email": "dana.reyes@example.com",
}
r = httpx.post("http://127.0.0.1:8000/jobs", json=job)
print(r.status_code)
print(json.dumps(r.json(), indent=2))

Output:

200
{
  "title": "Data Analyst",
  "city": "Austin",
  "salary": 92500.0,
  "posted_on": "2026-12-10",
  "remote": true,
  "recruiter_email": "dana.reyes@example.com"
}
Command Prompt output of a FastAPI POST request returning status 200 and echoing the job including the recruiter email
Status 200, and the private email comes back.

"2026-12-10" arrived as text, and the date type hint converted and validated it.

Checkpoint: You should see 200 and all six fields, including recruiter_email.

Step 3: Return 201 Created with status_code

A 200 only says the request worked, while 201 says a new record now exists. We’ll also store the job in a list and give it an ID. Replace the route in main.py:

JOBS = []


@app.post("/jobs", status_code=201)
def create_job(job: JobIn):
    record = {"id": len(JOBS) + 1, **job.model_dump()}
    JOBS.append(record)
    return record

status_code goes on the decorator, not the function. model_dump() turns the model into a dict (it replaced the older Pydantic v1 .dict()).

Output:

201
{
  "id": 1,
  "title": "Data Analyst",
  "city": "Austin",
  "salary": 92500.0,
  "posted_on": "2026-12-10",
  "remote": true,
  "recruiter_email": "dana.reyes@example.com"
}
Command Prompt output of a FastAPI POST request returning status 201 with a new id of 1
201 and an ID, but the email’s still exposed.

Checkpoint: The first line now reads 201 and the job has "id": 1. The list empties whenever the server restarts.

Step 4: Hide private fields with response_model

Callers shouldn’t get the recruiter’s email back. Add a second model under JobIn, then name it on the decorator:

class JobOut(BaseModel):
    id: int
    title: str
    city: str
    salary: float
    posted_on: date
    remote: bool
@app.post("/jobs", status_code=201, response_model=JobOut)

FastAPI filters the return value down to the declared fields, and the same model documents the response in /docs.

Output:

201
{
  "id": 1,
  "title": "Data Analyst",
  "city": "Austin",
  "salary": 92500.0,
  "posted_on": "2026-12-10",
  "remote": true
}
Command Prompt output of a FastAPI POST request with response_model removing the recruiter email from the JSON
Same request, and recruiter_email is gone from the response.

Test the POST Endpoint in Swagger /docs

Open http://127.0.0.1:8000/docs. FastAPI builds this page from your code, and both models appear under Schemas.

Swagger UI at /docs listing the FastAPI POST /jobs endpoint with the JobIn and JobOut schemas
The POST route and both Pydantic models.
  1. Expand POST /jobs.
  2. Click Try it out.
  3. Replace the sample JSON with your job.
  4. Click Execute.
Swagger UI Try it out panel for FastAPI POST /jobs with a JSON job in the request body editor
The request body, ready to execute.

You’ll get the 201 from the first screenshot. Now delete the salary line and execute again:

Swagger UI showing a FastAPI POST request rejected with 422 because the salary field is missing
FastAPI rejects the body before your function runs.

Troubleshooting: why does a FastAPI POST return 422?

A 422 means the body didn’t match the model, so you don’t have to check variable types by hand. This script triggers the mistakes I see most often:

import httpx

URL = "http://127.0.0.1:8000/jobs"
job = {
    "title": "QA Engineer",
    "city": "Denver",
    "salary": 78000.00,
    "posted_on": "2026-12-10",
    "recruiter_email": "marcus.hale@example.com",
}


def show(label, r):
    d = r.json()["detail"]
    if isinstance(d, list):
        d = f'{d[0]["loc"]} {d[0]["msg"]}'
    print(f"{label}: {r.status_code} {d}")


no_salary = {k: v for k, v in job.items() if k != "salary"}
show("missing field", httpx.post(URL, json=no_salary))
show("wrong type", httpx.post(URL, json={**job, "salary": "a lot"}))
show("form data", httpx.post(URL, data=job))
show("browser GET", httpx.get(URL))

Output:

missing field: 422 ['body', 'salary'] Field required
wrong type: 422 ['body', 'salary'] Input should be a valid number, unable to parse string as a number
form data: 422 ['body'] Input should be a valid dictionary or object to extract fields from
browser GET: 405 Method Not Allowed
Command Prompt output of FastAPI POST requests returning 422 validation errors and 405 Method Not Allowed
Three 422 responses and a 405.
ProblemFix
422 Field requiredSend every field with no default.
422 from form dataSend JSON with json=, not data=.
405 in the browserThe route accepts POST only, so use a script or /docs.

Where to Take It Next

A couple more pages worth keeping open while you build:

Frequently asked questions

How do I create a POST endpoint in FastAPI?

Define a Pydantic model, then decorate a function with @app.post("/path") and type one parameter as that model.

How do I return 201 from a FastAPI POST?

Add status_code=201 to the decorator. status.HTTP_201_CREATED from fastapi is the same value.

What’s the difference between the input model and response_model?

The parameter’s model validates what comes in. response_model validates and filters what goes out.

Can I send a body with a GET request instead?

Avoid it. The behavior isn’t defined by the spec, and Swagger UI won’t document it, so send data with POST.

Where’s the official reference for request bodies?