### Install Intent API Backend (Python)
Source: https://www.intentapi.dev/docs
Install the Intent API Python package using pip. This is the backend component.
```bash
pip install intent-api
```
--------------------------------
### React Frontend Integration
Source: https://www.intentapi.dev/docs
Example of integrating Intent API into a React frontend using the `@intent-api/react` package, including provider setup and usage of query and mutation hooks.
```APIDOC
## React Frontend Setup
### Description
This snippet shows how to integrate the Intent API into a React application using the `@intent-api/react` package. It covers setting up the `IntentApiProvider` and using hooks like `useIntentQuery` and `useIntentMutation`.
### Method
N/A (Client-side setup)
### Endpoint
N/A (Client-side setup)
### Parameters
N/A
### Request Body
N/A
### Request Example
N/A
### Code Example
```jsx
import { IntentApiProvider, useIntentQuery, useIntentMutation, intentFactory } from "@intent-api/react";
// Wrap your application with IntentApiProvider
(await getToken()) ?? null} // Function to get auth token
defaultContext={{ type: "user" }} // Default context for all requests
>
// Example usage in a component:
function MyComponent() {
// Fetch a list of todos
const { data } = useIntentQuery("Todo", "list", { skip: 0, limit: 20 });
// Get a mutation hook to create a todo
const createTodo = useIntentMutation("Todo", "create");
// Function to handle todo creation
const handleCreateTodo = () => {
createTodo.mutate(intentFactory("Todo", "create", { payload: { title: "Hi" } }));
};
return (
{/* Render your todo list and create button */}
);
}
```
### Notes
Query keys are structured as `["intent", model, ...]` which allows for easy invalidation after mutations.
```
--------------------------------
### Install Intent API Frontend (React)
Source: https://www.intentapi.dev/docs
Install the Intent API React package using npm. Peer dependencies include React, TanStack Query, and Axios.
```bash
npm install @intent-api/react
# peer: react, @tanstack/react-query, axios
```
--------------------------------
### Intent Protocol Example
Source: https://www.intentapi.dev/docs
Example of a typical user-facing POST request body for the Intent API, specifying model, action, payload, and context.
```json
{
"model": "Todo",
"action": "create",
"payload": { "title": "Ship Intent API", "done": false },
"context": { "type": "user", "team_id": "abc-123" }
}
```
--------------------------------
### React Intent API Provider and Hooks
Source: https://www.intentapi.dev/docs
Example of setting up the Intent API Provider in a React app and using useIntentQuery and useIntentMutation hooks. The provider requires baseURL, getToken, and defaultContext.
```javascript
import { IntentApiProvider, useIntentQuery, useIntentMutation, intentFactory } from "@intent-api/react";
(await getToken()) ?? null}
defaultContext={{ type: "user" }}
>
const { data } = useIntentQuery("Todo", "list", { skip: 0, limit: 20 });
const createTodo = useIntentMutation("Todo", "create");
createTodo.mutate(intentFactory("Todo", "create", { payload: { title: "Hi" } }));
```
--------------------------------
### Python (FastAPI) Backend Integration
Source: https://www.intentapi.dev/docs
Example of how to integrate Intent API into a Python FastAPI backend by subclassing IntentService and registering it with IntentRouter.
```APIDOC
## Python Backend Setup
### Description
This snippet demonstrates how to set up a Python backend using FastAPI with the Intent API. It involves creating a service class that inherits from `IntentService` and registering it with `IntentRouter`.
### Method
N/A (Server-side setup)
### Endpoint
N/A (Server-side setup)
### Parameters
N/A
### Request Body
N/A
### Request Example
N/A
### Response
N/A
### Code Example
```python
from fastapi import FastAPI
from intent_api import IntentRouter, IntentService, MutationResponse
app = FastAPI()
class TodoService(IntentService):
async def create(self, *, db, user, context, payload):
# Your logic to create a todo item
return MutationResponse(success=True, id="1", message="Todo created")
async def list(self, *, db, user, context, skip, limit):
# Your logic to list todo items
return {"items": [], "total": 0}
router = IntentRouter()
router.register("Todo", TodoService())
app.include_router(router.build(
get_user=my_auth_dependency, # Replace with your authentication dependency
get_db=my_db_dependency, # Replace with your database dependency
))
```
```
--------------------------------
### React Multiple Surface Hooks
Source: https://www.intentapi.dev/docs
Example of using different hooks for various surfaces like admin, guest, and machine. These hooks correspond to different backend endpoint prefixes.
```javascript
useIntentQuery("Todo", "list");
useAdminIntentQuery("User", "list");
useGuestIntentQuery("Post", "list");
useMachineIntentMutation("Event", "ingest_batch");
```
--------------------------------
### Python FastAPI Intent Service
Source: https://www.intentapi.dev/docs
Example of a Python FastAPI backend service using Intent API. Subclass IntentService, register with IntentRouter, and include the router in your FastAPI app.
```python
from fastapi import FastAPI
from intent_api import IntentRouter, IntentService, MutationResponse
app = FastAPI()
class TodoService(IntentService):
async def create(self, *, db, user, context, payload):
return MutationResponse(success=True, id="1", message="Todo created")
async def list(self, *, db, user, context, skip, limit):
return {"items": [], "total": 0}
router = IntentRouter()
router.register("Todo", TodoService())
app.include_router(router.build(
get_user=my_auth_dependency,
get_db=my_db_dependency,
))
```
--------------------------------
### Multiple Surfaces (Backend & Frontend)
Source: https://www.intentapi.dev/docs
Demonstrates how to handle different user roles or access levels (e.g., admin, guest, machine) by using specialized hooks and backend router builders.
```APIDOC
## Multiple Surfaces
### Description
Intent API supports handling different access levels or user roles through multiple surfaces. This is achieved on the backend using different router builders (e.g., `build_admin`, `build_guest`) and on the frontend using corresponding hooks (e.g., `useAdminIntentQuery`, `useGuestIntentQuery`).
### Method
N/A
### Endpoint
Default paths are `/api/intent`, `/api/admin-intent`, `/api/guest-intent`, etc. These can be overridden in the `IntentApiProvider`'s `endpoints` configuration.
### Parameters
N/A
### Request Body
N/A
### Request Example
N/A
### Backend Example
```python
# Example using different router builders for different surfaces
# app.include_router(router.build_admin(...))
# app.include_router(router.build_guest(...))
# app.include_router(router.build_machine(...))
```
### Frontend Example
```jsx
import { useAdminIntentQuery, useGuestIntentQuery, useMachineIntentMutation } from "@intent-api/react";
// Admin specific query
const { data: adminData } = useAdminIntentQuery("User", "list");
// Guest specific query
const { data: guestData } = useGuestIntentQuery("Post", "list");
// Machine specific mutation
const ingestEvent = useMachineIntentMutation("Event", "ingest_batch");
```
```
--------------------------------
### Intent API - Core Endpoint
Source: https://www.intentapi.dev/docs
The core Intent API endpoint handles all requests via a POST method. It accepts a JSON body defining the model, action, payload, and context.
```APIDOC
## POST /api/intent
### Description
This is the primary endpoint for sending typed intents to the Intent API. It allows clients to specify the resource (model), the desired operation (action), the data involved (payload), and the operational scope (context).
### Method
POST
### Endpoint
/api/intent
### Request Body
- **model** (string) - Required - The name of the resource, e.g., "Todo", "User".
- **action** (string) - Required - The operation to perform, e.g., "create", "read", "update", "delete", "list", "custom".
- **id** (string) - Optional - The identifier for a specific resource when the action is "read", "update", or "delete".
- **payload** (object) - Optional - The data associated with the action, typically used for "create" or "update" operations, or custom commands.
- **command** (string) - Optional - The name of a custom command to execute when the action is "custom".
- **context** (object) - Optional - Information about the caller's scope, such as role, team, or organization.
- **skip** (integer) - Optional - Used for pagination with the "list" action to specify the number of records to skip.
- **limit** (integer) - Optional - Used for pagination with the "list" action to specify the maximum number of records to return.
### Request Example
```json
{
"model": "Todo",
"action": "create",
"payload": { "title": "Ship Intent API", "done": false },
"context": { "type": "user", "team_id": "abc-123" }
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **id** (string) - The ID of the created or modified resource.
- **message** (string) - A message describing the result of the operation.
- **items** (array) - A list of resources, typically returned for "list" actions.
- **total** (integer) - The total number of items available for "list" actions.
#### Response Example
```json
{
"success": true,
"id": "1",
"message": "Todo created"
}
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.