Skip to main content
Version: v7.0.0

URL Parameters

Many API endpoints use dynamic URL segments to identify resources, like /users/:userId. Hyper-fetch automatically infers these URL parameters from the endpoint string, providing full type safety. This means you'll get compile-time errors if you forget to provide a required parameter or use the wrong type, making your requests much safer.

What you'll learn
  1. How Hyper-fetch infers URL parameters from the endpoint string.
  2. The two ways to provide parameters: via .setParams() or in the .send() method.
  3. How to work with multiple URL parameters in a single request.

Why is it helpful?

  • Route Correctness: Guarantees that dynamic URL segments are always provided, preventing 404 errors from malformed URLs.
  • Type Safety: Ensures that parameters are provided, catching potential issues at compile-time.
  • Compile-Time Checks: Catches missing or misspelled parameters during development, not in production.
  • Improved Readability: The request definition clearly shows which parameters are required for the endpoint to function.

Example

Hyper-fetch parses the endpoint string to automatically infer the required URL parameters, making them type-safe.

// import { createClient } from '@hyper-fetch/core';

export const client = createClient()({
url: "https://api.example.com",
});

// 1. Define the response type
type User = { id: number; name: string };
type ResponseType = User;

// 2. Create a request with a dynamic URL parameter
// Hyper-fetch infers that `userId` is a required parameter.
const getUser = client.createRequest<{ response: ResponseType }>()({
endpoint: "/users/:userId",
});

// 3. Provide the parameter using the `.send()` method
// The `params` object is strongly typed. Try renaming `userId` to see an error.
const { data: user1 } = await getUser.send({
params: { userId: 1 },
});

// 4. Alternatively, provide the parameter using `.setParams()` for reusability
const getUser1 = getUser.setParams({ userId: 1 });
const { data: user1Again } = await getUser1.send();

// 5. Example with multiple parameters
const getComment = client.createRequest()({
endpoint: "/posts/:postId/comments/:commentId",
});

const { data: comment } = await getComment.send({
params: {
postId: 10,
commentId: 2,
},
});

Congratulations!

You're now an expert in URL parameters!

  • You can let Hyper-fetch automatically infer path parameters from your endpoint.
  • You know how to provide parameters either by chaining .setParams() or passing them to .send().
  • You can confidently work with endpoints that require multiple URL parameters.