By Fikra DevRel • 4 min read

React Native Integration with Fikra API

React Native Integration with Fikra API

Overview

React Native does not have a native OpenAI SDK. However, because Fikra API provides an OpenAI-compatible chat-completions interface, you can integrate it using standard HTTP requests or by using the openai JavaScript SDK in a React Native environment (if supported by your build setup) or a lightweight HTTP client like axios or fetch.

This guide demonstrates a direct HTTP integration using fetch, which is natively supported in React Native.

Prerequisites

  1. A Fikra API account with a valid API key.
  2. A React Native project.
  3. Node.js and npm/yarn for package management.

Environment Variable Setup

Store your API key in an environment variable. In React Native, you can use react-native-config or manage secrets via a secure storage solution. For this example, assume the key is available as FIKRA_API_KEY.

// Example: Using react-native-config
import Config from 'react-native-config';

const FIKRA_API_KEY = Config.FIKRA_API_KEY;
const FIKRA_BASE_URL = 'https://api.fikraapi.co.ke/v1';

Basic Integration Example

Use the fetch API to send a POST request to the /chat/completions endpoint.

async function getChatCompletion() {
  const response = await fetch('https://api.fikraapi.co.ke/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${FIKRA_API_KEY}`
    },
    body: JSON.stringify({
      model: 'fikra-flash',
      messages: [
        { role: 'user', content: 'Hello, Fikra!' }
      ]
    })
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  const data = await response.json();
  console.log(data.choices[0].message.content);
}

Streaming Guidance

To enable streaming, set stream: true in the request body. The response will be in Server-Sent Events (SSE) format. You can read the stream using response.body.getReader().

async function getStreamingChatCompletion() {
  const response = await fetch('https://api.fikraapi.co.ke/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${FIKRA_API_KEY}`
    },
    body: JSON.stringify({
      model: 'fikra-flash',
      messages: [
        { role: 'user', content: 'Hello, Fikra!' }
      ],
      stream: true
    })
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    const chunk = decoder.decode(value);
    // Process SSE chunks
    console.log(chunk);
  }
}

Common Errors

  • 400 Bad Request: Invalid request format or missing required fields.
  • 401 Unauthorized: Invalid or missing API key.
  • 402 Payment Required: Insufficient token credits in your wallet.
  • 429 Too Many Requests: Rate limit exceeded. Unverified accounts are limited to 30 RPM, and trusted accounts to 100 RPM.
  • 503 Service Unavailable: Temporary server issue. Retry with exponential backoff.

Production Checklist

  1. Secure API Keys: Never hardcode API keys in client-side code. Use a backend proxy to hide your API key from the client.
  2. Error Handling: Implement robust error handling for all HTTP status codes.
  3. Rate Limiting: Monitor your usage to stay within the 30 RPM (unverified) or 100 RPM (trusted) limits.
  4. Streaming: Use streaming for better user experience in chat applications.
  5. Testing: Test your integration thoroughly in both development and production environments.
  6. Monitoring: Set up logging and monitoring to track API usage and errors.

JM
// The Founder

James Miano

CTO & ML Engineer at Lacesse Ventures. James specializes in low-overhead LLM quantization processes, custom ternary weights architectures, and localized server optimization.

Stop paying for overpriced round-trip latency

Why route queries over Western servers when you can use low-overhead hardware located in Nairobi? Save 87% on your monthly inference spend. No minimum credit limits. M-Pesa ready.

usagestatusdashboard