Backend & APIs

Configure and integrate backend services and APIs.

The project uses Expo API Router to create tRPC server endpoints.

tRPC ensures type-safe API communication between the frontend and backend, allowing a unified codebase that supports both the mobile app and web app, which simplifies development and maintains consistent data handling.

Project Structure

The project is organized to clearly separate frontend and backend code, with a shared codebase for common logic.

.env
package.json
  • packages/api/: Contains all backend-related files, including tRPC routers and context setup.
  • packages/db: Contains the db setup, including the migration configuration.

Defining new API route

Create and configure a new API route using tRPC. This example shows how to define a route that fetches user preferences.

routes.ts
import { protectedProcedure, router } from "@app/api";
 
export const userRouter = router({
  getPreferences: protectedProcedure.output(
    z.object({
      theme: z.string(),
      language: z.string(),
    })
  )
  .query( async(opts)=> {
      // Fetch and return user data
      return { theme: 1, language: 'en' };
  })
  // The reset of the routes
});

Calling the Query in React Components

Fetch and display data from the API in React components. This example demonstrates how to use the trpc hook to retrieve user preferences and handle loading and data states.

import { trpc } from '@app/api';
 
const UserPreferences = () => {
  const { data, isLoading } = trpc.user.getPreferences.useQuery();
 
  if (isLoading) return <Text>Loading...</Text>;
  if (!data) return <Text>No user data</Text>;
 
  return (
    <View>
      <Text>Theme : {data.theme}</Text>
      <Text>Language: {data.language}</Text>
    </View>
  );
};

Exposing the Query in OpenAPI Documentation

Add metadata to your API route to make it visible in OpenAPI documentation. This example shows how to document an endpoint that returns user preferences, including the method, path, and summary.

routes.ts
 
 getPreferences: protectedProcedure
 .input(z.void())
 .output(
    z.object({
      theme: z.string(),
      language: z.string(),
    })
  )
  .meta({
    openapi: {
      method: "Get",
      path: "/user/preferences",
      tags: ["user"],
      summary: "Returns the preferences of the logged-in user.",
    },
  })  
  .query( async(opts)=> {
      // Fetch and return user data
      return { theme: "dark", language: 'en' };
  }),

OpenAPI

Provide both .input() and .output() zod schemas to make the route visible in the OpenAPI documentation.

Without these, the route will not appear in the OpenAPI documentation.

You can view the new route in the OpenAPI documentation at http://localhost:8081/swagger

Swagger UI

On this page

sidecard

No native development experience? No problem.

Use your existing web dev skills to get your app on the store!