# Sending data

> Query strings, HTML forms and JSON bodies.

Source: https://aminbytes.dev/bytes/http/requests/sending-data/


There are three common ways to send data to a server.

## 1. In the URL: query strings

Good for **filters, search terms and pagination** on `GET` requests:

```http
GET /products?category=books&sort=price&page=2 HTTP/1.1
Host: shop.example.com
```

> [!WARNING]
> URLs end up in browser history, server logs and analytics. Never put passwords or tokens in a query string.

## 2. In the body: HTML forms

A plain HTML form sends its fields in the body, encoded like a query string:

```html {title="login.html"}
<form method="post" action="/login">
  <input name="email" type="email">
  <input name="password" type="password">
  <button>Log in</button>
</form>
```

Submitting it sends:

```http {hl_lines="3 6"}
POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 41

email=amin%40example.com&password=hunter2
```

For file uploads, the form uses `enctype="multipart/form-data"`, which splits the body into parts so binary files fit.

## 3. In the body: JSON

APIs usually send **JSON**. The `Content-Type` header tells the server how to read the body:

```http
POST /api/todos HTTP/1.1
Host: api.example.com
Content-Type: application/json
Content-Length: 43

{"title": "Learn HTTP", "completed": false}
```

From the terminal:

```bash
curl -X POST https://httpbin.org/post \
  -H "Content-Type: application/json" \
  -d '{"title": "Learn HTTP", "completed": false}'
```

From JavaScript:

```js {title="create-todo.js"}
const res = await fetch("/api/todos", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Learn HTTP", completed: false }),
});
```

## Which one when?

| You want to…                          | Use |
| ------------------------------------- | --- |
| Filter or search, shareable as a link | Query string on `GET` |
| Submit a simple HTML form             | `application/x-www-form-urlencoded` |
| Upload files                          | `multipart/form-data` |
| Talk to an API                        | `application/json` |


## Byte check

1. Where should the search term for a shareable results page go?
   - **In the query string of a `GET`** (correct)
   - In a JSON body of a `POST`
   - In a cookie
   Query strings are part of the URL, so the result can be bookmarked and shared.

2. Why should a password never go in a query string?
   - It's too long
   - **URLs end up in browser history, server logs and analytics** (correct)
   - Query strings can't hold symbols
   Put secrets in the body (over HTTPS) or in headers instead.

3. Which `Content-Type` does a form use to upload files?
   - `application/json`
   - **`multipart/form-data`** (correct)
   - `application/x-www-form-urlencoded`
   It splits the body into parts, so binary files fit next to the other fields.


