Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

Your First Stripe API Request

Make your first Stripe-style API request with fetch. Learn bearer authentication, form-encoded bodies, response objects, error types and why the HTTP status matters.

Stripe's API is an ordinary REST-style HTTP API. There is nothing magical about the official libraries: they build an HTTP request, send it to https://api.stripe.com, and turn the JSON answer into objects. Understanding the raw request makes every SDK feature, and every error message, easier to read. In this lesson you will build a request by hand and send it to a local stand-in server that mimics Stripe's rules.

The shape of a request

A real call to create a customer looks like this with curl (read-only; it would need a real key):

Terminal
curl https://api.stripe.com/v1/customers \
  -u sk_test_YOUR_KEY: \
  -d name="Ada Lovelace" \
  -d email="[email protected]"

Three details matter:

  1. Authentication: the secret key travels in the Authorization header, either as HTTP Basic auth (key as username, empty password, which is what -u does) or as Authorization: Bearer sk_test_....
  2. Form encoding: request bodies are application/x-www-form-urlencoded, not JSON. Nested data uses bracket notation, for example metadata[order_id]=A-1043.
  3. Responses are JSON, with an object field naming the type and an id for the thing created.

Sending JSON to the v1 API is a classic beginner mistake. The official SDKs encode the form body for you, but when you use fetch you must do it yourself.

Encoding nested parameters

URLSearchParams handles flat data. Stripe's nested objects and arrays need brackets: metadata[plan]=pro and items[0][price]=price_123. A small helper does it.

Node.js Encode nested params the Stripe way

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Arrays of objects use numeric indexes (line_items[0][price]), exactly what the helper produces.

A local stand-in server

Now send a real HTTP request, but to a stand-in server on 127.0.0.1 that follows Stripe's conventions: it checks the bearer key, parses a form body, returns a customer object, and returns a Stripe-shaped error when something is wrong. Piston gives programs a loopback network, so this runs here.

Node.js Create a customer against a stand-in server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the four results. The first is a customer object. The other three show the error responses you must learn to handle.

HTTP status codes in the Stripe API

Status Meaning What you should do
200 Success Use the returned object
400 Bad parameters Fix the request; do not retry unchanged
401 Bad or missing key Check the key and its mode
402 Request valid but failed, for example a declined card Show the customer a message
404 Unknown resource Check the ID and mode (test IDs do not exist in live)
409 Conflict, for example idempotency key reuse Read the message
429 Too many requests Back off and retry later
5xx Problem at Stripe Retry safely, using idempotency keys

The error body always has an error object with type, usually message, often code (a machine-readable reason such as card_declined) and param (which field was wrong). Show customers the message for card errors; log everything else and show a generic apology.

Reading an error in code

JavaScript
// Real SDK usage (read-only).
try {
  await stripe.customers.create({ name: "Ada" });
} catch (err) {
  switch (err.type) {
    case "StripeCardError":
      console.log("Declined:", err.message); // safe to show
      break;
    case "StripeInvalidRequestError":
      console.log("Bug in our request:", err.param);
      break;
    case "StripeRateLimitError":
      // retry later
      break;
    default:
      throw err;
  }
}

Always keep the request ID. Stripe returns it in the Request-Id response header (and as err.requestId in the SDK). Quote it when you ask support for help; they can find your exact call.

You now know what an SDK does under the hood. Next, see what the SDK adds on top: The Node SDK, Versions and Pagination.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Stripe's v1 API expect a request body to be encoded?

    The v1 API takes form-encoded bodies, with brackets for nested data. Responses are JSON.
  2. 2. Which parameter string represents nested metadata?

    Bracket notation is used for nested objects and numeric indexes for arrays.
  3. 3. A request returns HTTP 401. What is the most likely cause?

    401 means authentication failed. Check the key, and that its mode matches your data.
  4. 4. Which status should you retry unchanged without worry, using an idempotency key?

    Server errors are often temporary. 400, 401 and 404 will fail the same way until you fix the request.

Summary

  • The API is HTTP: bearer key in Authorization, form-encoded body, JSON response.
  • Nested data uses brackets: metadata[plan]=pro, line_items[0][price]=....
  • Learn the status codes: 400 fix it, 402 declined, 429 slow down, 5xx retry.
  • Keep the Request-Id for debugging.
  • The stand-in server taught the protocol; real calls need real keys.

Next: The Node SDK, Versions and Pagination