Thuta Learning
API Tutorial
AdvancedWeb DevelopmentIntermediate

Create User

API TutorialLesson 1535 min

What you'll walk away with

  • Send a JSON POST and read the 201 response, its Location header and the created resource
  • Return validation failures as 422 with one message per field, and tell them apart from a 400 for malformed JSON
  • Use 409 for a duplicate email after normalising it
  • Explain why the server allowlists writable fields and never trusts id or role from the body

Explain it simply

Creating a user in plain language

Creating a user is like filling in a sign-up form at a front desk. You hand over the details (name, email). The clerk checks the form, writes a new record, gives it a number you did not choose, and tells you where to find it: "Created, your file is at /v1/users/u_2". If something on the form is wrong, the clerk hands it back with a note for each field instead of quietly throwing it away.

In HTTP terms you send POST /v1/users with a JSON body. On success the server answers 201 Created, puts the URL of the new resource in a Location header, and returns the new user in the body, including the id it generated.

Problem → Why → Solution

The problem: an endpoint that saves whatever arrives

A typical first version of a create endpoint saves whatever JSON arrives. A client that sends {"name": "Mallory", "email": "m@example.com", "role": "admin"} has just made itself an administrator, because the object went straight into the database. The same endpoint answers 200 on success, answers 500 with a stack trace when the email is missing, and cheerfully stores two accounts for Bob@Example.com and bob@example.com. Each of these is a different bug: privilege escalation, a useless error and a duplicate.

save-everything.js
// Saves whatever the client sends
app.post("/v1/users", async (req, res) => {
  const user = await db.users.insert(req.body); // id, role, anything
  res.json(user);                               // 200, no Location header
});

The server owns the rules

Everything in a request body is chosen by the client, and the client may be a script written by an attacker. The server decides which fields a client may set (the allowlist), what counts as valid, and what the response says. This must happen on the server even if your own form already validates, because nobody is forced to use your form.

Core concept: POST to a collection and point at the result

POST /v1/users means "add a new member to the users collection". The client does not choose the URL or the id of the new resource, so POST goes to the collection and the server tells you where the resource now lives. Success is 201 Created with a Location header holding the new URL and, usually, the full resource in the body, so the client does not need a second GET. POST is not idempotent: unless the server prevents it, sending the same request twice creates two users.

Validation fails in layers, and each layer has its own status. If the body is not valid JSON, or the Content-Type is wrong, the server cannot even read the request: 400 Bad Request. If it parses but a value is unacceptable (an empty name, a malformed email), answer 422 and list every problem at once, one message per field, so the user can fix the whole form in one round trip. If the values are fine but the request clashes with existing data (the email already belongs to another user), answer 409 Conflict. Normalise before you compare: trim whitespace and lowercase the email, otherwise Bob@Example.com and bob@example.com become two accounts.

SituationStatuserror.code
Created201(user in the body, Location header)
Body is not valid JSON400invalid_json
Missing name, malformed email422validation_failed + fields
Email already in use409email_taken

Build the new record from an explicit list of allowed fields (name, email, bio) and give everything else a server-side value: the server generates the id and role is "member". Extras in the body such as role: "admin" are ignored here, while stricter APIs reject them with 422. Either way, the client can never choose a protected field. If the API accepts a password, hash it with an algorithm built for passwords such as argon2 or bcrypt and never return it. Also make the uniqueness check and the insert one atomic step (a transaction or a database unique constraint), otherwise two requests that arrive at the same instant can both pass an "is it taken?" check.

Fill in, check, file, point to it
  1. Client sends a JSON body with POST
  2. Server validates: 400, 422 or 409
  3. Server builds the record and its id
  4. 201 Created + Location + new user

The client proposes values; the server decides ids, roles and whether the request is acceptable.

General pattern

text
POST /v1/<collection>
Content-Type: application/json

{ <writable fields only> }

201 Created
Location: /v1/<collection>/<new id>
{ <the created resource, including server-set fields> }

The request carries only fields the client may write; the response carries the whole resource, including fields the server generated such as the id, plus the URL where it can be fetched.

Worked example: creating users and following Location

This sample runs a small users API on a random local port. It starts with Alice (u_1, the admin) and makes six calls: a valid POST that returns 201 and a Location header, a GET that follows that Location, an attempt to sneak in role: admin that is ignored, a 422 with two field messages, a 409 for the same email in different capitalisation, and a request whose body is not JSON. The output is the same on every run.

users-create.mjs
import http from "node:http";

// The users API (stands in for https://api.example.com/v1/users)
const users = new Map();
users.set("u_1", {
  id: "u_1",
  name: "Alice",
  email: "alice@example.com",
  role: "admin",
  bio: null,
});
let nextId = 2;

const send = (res, status, body, headers = {}) => {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(body));
};
const fail = (res, status, code, message, fields) =>
  send(res, status, { error: { code, message, ...(fields && { fields }) } });
const looksLikeEmail = (s) => typeof s === "string" && /^[^@ ]+@[^@ ]+[.][^@ ]+$/.test(s);

async function readJsonObject(req) {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  try {
    const value = JSON.parse(raw);
    return value?.constructor === Object ? value : null; // plain objects only
  } catch {
    return null;
  }
}

const server = http.createServer(async (req, res) => {
  const { pathname } = new URL(req.url, "http://localhost");
  const [, , resource, id] = pathname.split("/");
  if (resource === "users" && req.method === "GET" && id) {
    const user = users.get(id);
    if (!user) return fail(res, 404, "user_not_found", "No user " + id);
    return send(res, 200, user);
  }
  if (resource !== "users" || req.method !== "POST" || id) {
    return fail(res, 404, "not_found", "No such route");
  }

  const input = await readJsonObject(req);
  if (!input) return fail(res, 400, "invalid_json", "Body must be a JSON object");

  // Validate everything, then report every problem at once
  const fields = {};
  const name = typeof input.name === "string" ? input.name.trim() : "";
  if (!name) fields.name = "is required";
  if (!looksLikeEmail(input.email)) fields.email = "must be a valid email address";
  if (Object.keys(fields).length) {
    return fail(res, 422, "validation_failed", "One or more fields are invalid", fields);
  }

  // Normalise first, then check uniqueness
  const email = input.email.trim().toLowerCase();
  if ([...users.values()].some((u) => u.email === email)) {
    return fail(res, 409, "email_taken", "A user with this email already exists");
  }

  // Allowlist: the client can set name, email and bio. id and role are ours.
  const bio = input.bio ?? null;
  const user = { id: "u_" + nextId++, name, email, role: "member", bio };
  users.set(user.id, user);
  send(res, 201, user, { Location: "/v1/users/" + user.id });
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + server.address().port;

// The client
async function post(payload) {
  const res = await fetch(base + "/v1/users", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: typeof payload === "string" ? payload : JSON.stringify(payload),
  });
  return { res, data: await res.json() };
}

const bob = await post({ name: "Bob", email: "Bob@Example.com", bio: "Loves APIs" });
console.log(bob.res.status, bob.res.headers.get("location"));
console.log(JSON.stringify(bob.data));

const again = await fetch(base + bob.res.headers.get("location"));
console.log("follow Location:", again.status, (await again.json()).name);

const carol = await post({ name: "Carol", email: "carol@example.com", role: "admin" });
console.log(carol.res.status, "role:", carol.data.role, "(the client asked for admin)");

const bad = await post({ name: "  ", email: "not-an-email" });
console.log(bad.res.status, bad.data.error.code, JSON.stringify(bad.data.error.fields));

const dup = await post({ name: "Bobby", email: "BOB@example.com" });
console.log(dup.res.status, dup.data.error.code);

const broken = await post("{ name: Bob");
console.log(broken.res.status, broken.data.error.code);
server.close();

Code breakdown

  1. Read the body safelyreturn value?.constructor === Object ? value : null; // plain objects only

    JSON.parse also accepts null, arrays and numbers, so only a plain object is allowed through. Without this check a body of null would crash on input.name.

  2. 400 before anything elseif (!input) return fail(res, 400, "invalid_json", "Body must be a JSON object");

    If the body cannot be read there is nothing to validate, so the request is rejected with 400 right here.

  3. 422 with one message per fieldif (!name) fields.name = "is required";

    Each invalid field goes into the fields object and checking continues, which is why the bad request gets messages for both name and email in one response.

  4. Normalise, then compareconst email = input.email.trim().toLowerCase();

    BOB@example.com is converted to bob@example.com before comparing, so changing the capitalisation cannot dodge the duplicate check. The stored value is lowercase as well.

  5. 409 for a conflictreturn fail(res, 409, "email_taken", "A user with this email already exists");

    The values are fine but clash with existing data, so this is 409 rather than 422. The client has to choose another email.

  6. Allowlist, 201 and Locationsend(res, 201, user, { Location: "/v1/users/" + user.id });

    The user object is built from name, email and bio plus the server's own id and role, so Carol's role: admin never makes it in. The response is 201 with a Location header.

You should see
201 /v1/users/u_2
{"id":"u_2","name":"Bob","email":"bob@example.com","role":"member","bio":"Loves APIs"}
follow Location: 200 Bob
201 role: member (the client asked for admin)
422 validation_failed {"name":"is required","email":"must be a valid email address"}
409 email_taken
400 invalid_json
How the server handles POST /v1/users
  1. Read the body and check it is a JSON object
  2. Validate name and email
  3. Normalise the email and check for duplicates
  4. Build the record from the allowlist, answer 201

Every step passes

201 Created with Location and the new user

A step fails

400, 422 or 409 with a JSON error body and nothing is saved

The users resource used in this chapter

The next three lessons (read, update and delete) keep working with this same resource, so the contract is fixed here once. The error shape is also always the same: { "error": { "code", "message", "fields"? } }. That is why one client-side error handler can serve every endpoint.

FieldWho sets itRules
idServeru_ plus a number, never changes
nameClientrequired, not empty
emailClientrequired, valid, unique, stored lowercase
roleServermember on creation, clients cannot write it
bioClientoptional, null when absent

Trying it yourself with curl

When you call a real API with curl, the -i flag also prints the response headers, which you need in order to see Location. Single quotes can be awkward in Windows PowerShell, so Git Bash or a Linux/macOS terminal is the easiest place to try this. api.example.com is an example domain; replace it with your API's URL.

bash
curl -i -X POST https://api.example.com/v1/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Bob","email":"bob@example.com"}'

# HTTP/1.1 201 Created
# Location: /v1/users/u_2
# {"id":"u_2","name":"Bob","email":"bob@example.com","role":"member","bio":null}

In real projects

Create endpoints in real projects

A sign-up create endpoint can be called by anyone on the internet, so real services add rate limits and CAPTCHAs to defend against abuse. The pattern in this lesson shows up in APIs such as Stripe and GitHub: new resources come back with a success status and a representation, and validation problems are reported per field. Whether a provider uses 422 or 400 for those problems differs, so check its docs.

  • A frontend form reads the fields of a 422 and shows each message next to its input, and shows a 409 as "an account with this email already exists".
  • Tests cover a valid request, a missing name, a malformed email, a duplicate email, a smuggled role and a body that is not JSON.
  • For clients that may retry, some APIs support an Idempotency-Key header so that resending after a network failure does not create two users.

Common mistakes

Common mistakes when creating users

Passing the request body straight to the database

Handing the whole body to an ORM create lets the client write role: "admin", the id or internal flags (mass assignment). Pick the allowed fields by name.

Reporting one error at a time

Stopping at the first problem makes the user resubmit the form three or four times. Check every field and return a single fields object.

Checking uniqueness without normalising

If Bob@Example.com and bob@example.com count as different, you get two accounts and password-reset emails that go to the wrong one. Trim and lowercase before comparing, and add a unique constraint in the database too.

Answering 200 with no Location

Answering 200 for a successful create leaves the client unable to tell whether a resource was created or an existing one returned. Use 201 and a Location header.

Best practices

Best practices

  • Keep the validation rules in one place so that frontend and backend share them.
  • Return the resource in the same shape a later GET /v1/users/u_2 will return.
  • Keep error codes stable; the wording of the message may change later.

Mini challenge

Write createUser yourself

Write createUser(users, body) without any HTTP server. It returns { status, headers, body } and sends nothing. Answer 400 when body is not a plain object, 422 with one message per invalid field, 409 when the lowercased email is taken, and otherwise build the user from allowed fields and return 201 with a Location header.

  • 400 invalid_json when the body is not a plain object (arrays included)
  • name is required and email must look valid; otherwise 422 with fields
  • Trim and lowercase the email; 409 email_taken if it already exists
  • role is always member, a role in the body is ignored, Location is /v1/users/<id>
create-user.js
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com", role: "admin", bio: null },
];

function validate(body) {
  // TODO: return an object with one message per invalid field (empty when valid)
}

function createUser(users, body) {
  // TODO: 400 when body is not a plain object
  // TODO: 422 with { error: { code, message, fields } } when validate() finds problems
  // TODO: 409 when the lowercased email is already taken
  // TODO: otherwise build the user from allowed fields only and answer 201 + Location
  // Return { status, headers, body }; nothing is sent over a network here
}

Expected: Four lines print: first a 201 with the Location and role member, then 422, 409 and 400 with their error codes.

Show hint

A small helper that builds an error response can be reused for three of the four statuses. body?.constructor !== Object rejects arrays, null and strings in one check. The id can be built from users.length + 1.

Show solution
create-user-solution.js
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com", role: "admin", bio: null },
];

const problem = (status, code, message, fields) => ({
  status,
  headers: {},
  body: { error: { code, message, ...(fields && { fields }) } },
});

function validate(body) {
  const fields = {};
  if (typeof body.name !== "string" || !body.name.trim()) fields.name = "is required";
  const email = typeof body.email === "string" ? body.email.trim() : "";
  if (!email.includes("@") || !email.split("@")[1].includes(".")) {
    fields.email = "must be a valid email address";
  }
  return fields;
}

function createUser(users, body) {
  if (body?.constructor !== Object) {
    return problem(400, "invalid_json", "Body must be a JSON object");
  }
  const fields = validate(body);
  if (Object.keys(fields).length) {
    return problem(422, "validation_failed", "Invalid fields", fields);
  }
  const email = body.email.trim().toLowerCase();
  if (users.some((u) => u.email === email)) {
    return problem(409, "email_taken", "Email already used");
  }
  const user = {
    id: "u_" + (users.length + 1),
    name: body.name.trim(),
    email,
    role: "member",
    bio: body.bio ?? null,
  };
  users.push(user);
  return { status: 201, headers: { Location: "/v1/users/" + user.id }, body: user };
}

function show(result) {
  const b = result.body;
  const detail = b.error
    ? b.error.code + " " + JSON.stringify(b.error.fields ?? {})
    : b.id + " " + b.email + " " + b.role;
  console.log(result.status, result.headers.Location ?? "-", detail);
}

show(createUser(users, { name: "Dana", email: "Dana@Example.com", role: "admin" }));
show(createUser(users, { name: "", email: "dana" }));
show(createUser(users, { name: "Dan", email: "DANA@example.com" }));
show(createUser(users, [1, 2]));

Quick quiz 1 / 3

Which response is the most correct for a successful POST /v1/users?

Quick quiz 2 / 3

A client sends { "name": "Bob", "email": "bob@example" }. The JSON is valid. Which status fits best?

Quick quiz 3 / 3

alice@example.com already exists. A client creates a user with ALICE@Example.com. If the server compares emails without normalising them, what happens?

What to remember

  • POST to the collection (/v1/users); on success answer 201 Created with a Location header and the full resource.
  • 400 = body unreadable, 422 = bad values (a message per field), 409 = clash with existing data.
  • Trim and lowercase the email before comparing, and make the uniqueness check and the insert atomic.
  • Let clients write allowlisted fields only; the server generates id and role.

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.