Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
229 changes: 229 additions & 0 deletions challenges/data/04.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
# Generate a typed API client with Orval

## 📡 What you will learn

- Describe a REST API with an [OpenAPI](https://www.openapis.org/) spec.
- Generate typed `react-query` hooks with [Orval](https://orval.dev/).
- Send every request through one custom `fetch` function.

## 👾 Before we start the exercise

- [ ] Finish the [`react-query` challenge](./02.md): you need `QueryClientProvider` and your `useStarships()` hook.
- [ ] Have a look at the [Orval React Query guide](https://orval.dev/docs/guides/react-query)

In the previous challenge you wrote the API layer by hand: a `fetch` function, a `queryKey`, a `useQuery` hook and, for TypeScript, the `StarshipProps` type. It works for one endpoint, but every new endpoint repeats that code, and nothing tells you when your types no longer match the API.

An **OpenAPI spec** is a YAML (or JSON) file that describes an API: its URLs, its parameters and the shape of every response. **Orval** reads that spec and writes the API layer for you:

1. A typed `fetch` function per endpoint (_here `listStarships` and `getStarship`_).
1. A `queryKey` per endpoint, built from its URL and parameters.
1. A `react-query` hook per endpoint (_here `useListStarships` and `useGetStarship`_).
1. A TypeScript type per response (_here `Starship` and `StarshipList`_).

SWAPI doesn't publish an OpenAPI spec, so we wrote one for you: [`swapi.yml`](./swapi.yml). It describes the starships endpoints.

## 👨‍🚀 Exercise 4

### Add the OpenAPI spec

- [ ] Download the spec into an `api` folder at the root of your project

```console
mkdir -p api
curl -o api/swapi.yml https://raw.githubusercontent.com/flexbox/react-native-bootcamp/main/challenges/data/swapi.yml
```

- [ ] Take 5 min to **read carefully** `api/swapi.yml`:
- `paths` lists the endpoints: `/starships/` and `/starships/{id}/`.
- Each `operationId` becomes a function name: `listStarships` → `useListStarships()`.
- `components.schemas` describes the responses: each schema becomes a TypeScript type.

**🔭 Hint:** SWAPI returns every value as a string, numbers included (`"3500000"`, `"unknown"`, `"30-165"`). The spec types them as `string` so the generated types match what the API really sends.

### Install and configure Orval

- [ ] Install Orval as a dev dependency: it runs on your computer, not in the app

```console
npm install --save-dev orval
```

- [ ] Create the `fetch` function every generated request will go through

```ts
// ./src/api/fetcher.ts
export const swapiFetch = async <T>(
url: string,
options: RequestInit,
): Promise<T> => {
const response = await fetch(url, options);

if (!response.ok) {
// Throwing puts the query in its `isError` state
throw new Error(`SWAPI error ${response.status} on ${url}`);
}

return response.json();
};
```

`fetch` only rejects when the network fails. A `404` or a `500` still resolves, so we throw ourselves. This function is also the one place to add headers later, like an auth token.

**🔭 Hint:** Orval calls this function a [custom client](https://orval.dev/docs/guides/custom-client).

- [ ] Create `orval.config.ts` at the root of your project

```ts
// ./orval.config.ts
import { defineConfig } from "orval";

export default defineConfig({
swapi: {
input: "./api/swapi.yml",
output: {
// Reads `servers[0].url` from the spec: https://swapi.py4e.com/api
baseUrl: { getBaseUrlFromSpecification: true },
client: "react-query",
httpClient: "fetch",
// Hooks in swapi.ts, types in swapi.schemas.ts
mode: "split",
override: {
fetch: {
// Return the JSON body, like `swapiFetch` does
includeHttpResponseReturnType: false,
},
mutator: {
name: "swapiFetch",
path: "./src/api/fetcher.ts",
},
},
target: "./src/api/swapi.ts",
},
},
});
```

- [ ] Add a script to `package.json`

```json
"scripts": {
"api:generate": "orval"
}
```

- [ ] Generate the client

```console
npm run api:generate
```

You should now have two new files:

- `src/api/swapi.ts`: `listStarships`, `useListStarships`, `getStarship`, `useGetStarship`…
- `src/api/swapi.schemas.ts`: `Starship`, `StarshipList`, `ListStarshipsParams`…

**🔭 Hint:** Never edit these two files by hand: the next `npm run api:generate` overwrites them. To change the API layer, change `api/swapi.yml` or `orval.config.ts`, then generate again.

### Use the generated hooks

- [ ] In `StarshipFeedScreen`, replace your `useStarships()` hook with the generated `useListStarships()`

```tsx
// READ AND ADAPT; DO NOT MONKEY COPY/PASTE ME
import { useListStarships } from "@/api/swapi";

export const StarshipFeedScreen = () => {
const { data, isError, isPending, refetch } = useListStarships();

// …your loading and error states stay the same

return (
<FlatList
data={data.results} // typed as Starship[]
keyExtractor={(ship) => ship.url}
renderItem={renderItem}
/>
);
};
```

- [ ] Hover `data.results` in your editor: TypeScript now knows every field of a `Starship`. Try `data.results[0].nam` and look at the error.
- [ ] Replace your hand-written `StarshipProps` type with the generated `Starship` type

```ts
import type { Starship } from "@/api/swapi.schemas";
```

- [ ] Delete `fetchStarshipsData` and `useStarships.ts`: Orval generated them for you.

## 👽 Bonus

### Search

The `/starships/` endpoint takes a `search` parameter. The generated hook has a typed `params` argument for it, and puts it in the `queryKey` so each search is cached separately.

- [ ] Add a search field above the list and pass its value to the hook

```ts
const { data } = useListStarships({ search: "star" });
```

### Starship details

- [ ] Use `useGetStarship(id)` in `StarshipDetailsScreen` to load one starship.
- [ ] Call it with an id that doesn't exist, like `9999`. Thanks to `swapiFetch`, the `404` makes the query fail, so you can show your error state.

**🔭 Hint:** The `id` is the number at the end of the starship `url`: `https://swapi.py4e.com/api/starships/9/` → `9`.

### Infinite scroll

SWAPI returns 10 starships per page, and `next` holds the URL of the next page.

- [ ] Ask Orval for an infinite query hook in `orval.config.ts`, then run `npm run api:generate` again

```ts
override: {
// …
query: {
useInfinite: true,
useInfiniteQueryParam: "page",
},
},
```

- [ ] Load the next page when the user reaches the end of the `FlatList`

```tsx
// READ AND ADAPT; DO NOT MONKEY COPY/PASTE ME
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
useListStarshipsInfinite(undefined, {
query: {
initialPageParam: 1,
getNextPageParam: (lastPage) => {
if (!lastPage.next) {
return undefined; // last page
}
return Number(new URL(lastPage.next).searchParams.get("page"));
},
},
});

const starships = data?.pages.flatMap((page) => page.results) ?? [];

<FlatList
data={starships}
onEndReached={() => {
if (hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}}
// …
/>;
```

### Write your own endpoint

- [ ] Add the `/people/` endpoint to `api/swapi.yml`, with a `Person` schema built from a real response of [`https://swapi.py4e.com/api/people/1/`](https://swapi.py4e.com/api/people/1/).
- [ ] Generate the client again and use `useListPeople()` in your pilots screen.

**🔭 Hint:** Copy the `/starships/` path and the `StarshipList` schema, then adapt them. The `operationId` you choose becomes the hook name.
131 changes: 131 additions & 0 deletions challenges/data/swapi.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
openapi: 3.1.0
info:
title: Star Wars API – Starships
version: "1.0.0"
description: |
Starships from the Star Wars API (https://swapi.py4e.com).
SWAPI does not publish an OpenAPI spec: this one was written from its
live responses for the React Native bootcamp.
servers:
- url: https://swapi.py4e.com/api
tags:
- name: Starships

paths:
/starships/:
get:
tags: [Starships]
operationId: listStarships
summary: List starships (10 per page)
parameters:
- name: page
in: query
description: Page number, starting at 1.
schema: { type: integer, minimum: 1, default: 1 }
- name: search
in: query
description: Case-insensitive partial match on `name` or `model`.
schema: { type: string }
responses:
"200":
description: A page of starships
content:
application/json:
schema:
$ref: "#/components/schemas/StarshipList"

/starships/{id}/:
get:
tags: [Starships]
operationId: getStarship
summary: Get one starship
parameters:
- name: id
in: path
required: true
description: The number at the end of the starship `url`.
schema: { type: integer }
responses:
"200":
description: The starship
content:
application/json:
schema:
$ref: "#/components/schemas/Starship"
"404":
description: No starship with this id
content:
application/json:
schema:
$ref: "#/components/schemas/NotFound"

components:
schemas:
StarshipList:
type: object
required: [count, next, previous, results]
properties:
count: { type: integer, description: Total number of starships. }
next:
type: [string, "null"]
format: uri
description: URL of the next page, `null` on the last page.
previous:
type: [string, "null"]
format: uri
description: URL of the previous page, `null` on the first page.
results:
type: array
items: { $ref: "#/components/schemas/Starship" }

# SWAPI returns every value as a string, numbers included ("3500000",
# "unknown", "30-165"), so they are typed as strings here too.
Starship:
type: object
required:
- name
- model
- manufacturer
- cost_in_credits
- length
- max_atmosphering_speed
- crew
- passengers
- cargo_capacity
- consumables
- hyperdrive_rating
- MGLT
- starship_class
- pilots
- films
- created
- edited
- url
properties:
name: { type: string, example: CR90 corvette }
model: { type: string, example: CR90 corvette }
manufacturer: { type: string, example: Corellian Engineering Corporation }
cost_in_credits: { type: string, example: "3500000" }
length: { type: string, example: "150" }
max_atmosphering_speed: { type: string, example: "950" }
crew: { type: string, example: 30-165 }
passengers: { type: string, example: "600" }
cargo_capacity: { type: string, example: "3000000" }
consumables: { type: string, example: 1 year }
hyperdrive_rating: { type: string, example: "2.0" }
MGLT: { type: string, example: "60" }
starship_class: { type: string, example: corvette }
pilots:
type: array
items: { type: string, format: uri }
films:
type: array
items: { type: string, format: uri }
created: { type: string, format: date-time }
edited: { type: string, format: date-time }
url: { type: string, format: uri, example: "https://swapi.py4e.com/api/starships/2/" }

NotFound:
type: object
properties:
detail: { type: string, example: Not found }
11 changes: 11 additions & 0 deletions hackathon/spacecraft/.vscode/mcp.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"servers": {
"argent": {
"type": "stdio",
"command": "argent",
"args": [
"mcp"
]
}
}
}
Loading
Loading