API Documentation

Welcome to the API documentation for Koffieland. Here you will find all the information you need to get started with our API.

Koffieland
Koffieland
GitHub
ChatGPT
Chat-GPT
React
React
Python
Python

Welcome to the Koffieland API—an easy, RESTful solution built with FastAPI that uses JSON for data exchange. Secure your requests with an API key from your Koffieland account. Use the API to manage resources, redeem Digibeans for rewards like free drinks and discounts, and update your account details. Whether you're building custom apps or automating tasks, our flexible API has you covered. For support, join our community forum or contact our team.


from fastapi import FastAPI
app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

Digibean Redemption Form React Component

This is a React component for redeeming Digibeans. It sends a POST request to the specified API URL with the user's email and bean count. On success, it triggers the onSuccess callback with the API response.

The component uses state to manage the input values and loading/error states. It also includes basic form validation. The form submission is handled by the handleSubmit function, which sends a POST request to the API with the user's email and bean count. The component also includes error handling and displays any error messages to the user.

To use this component, you need to provide the API URL, API key, and a callback function to handle the success response. You can customize the component by passing different props to it. You can also customize the component by passing different props to it. The component is designed to be reusable and can be easily integrated into any React application.

Login to you Koffieland account and navigate to the API section to generate your API key. View redeem history and other details in the dashboard on Koffieland.

// DigibeanRedeemForm.jsx
import React, { useState } from 'react';

const DigibeanRedeemForm = ({ apiUrl, apiKey, onSuccess }) => {
  const [email, setEmail] = useState('');
  const [beanCount, setBeanCount] = useState('');
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': apiKey
        },
        body: JSON.stringify({
          email,         // For user matching or verification
          beanCount,     // The number of beans to redeem
          isAPI: true
        })
      });
      if (!response.ok) throw new Error('API error: ' + response.statusText);
      const result = await response.json();
      onSuccess(result);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <h2>Redeem Your Digibeans</h2>
      <div>
        <label>Email:</label>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
      </div>
      <div>
        <label>Bean Count:</label>
        <input
          type="number"
          value={beanCount}
          onChange={(e) => setBeanCount(e.target.value)}
          required
        />
      </div>
      <button type="submit" disabled={loading}>
        {loading ? 'Processing...' : 'Redeem'}
      </button>
      {error && <div style={{ color: 'red' }}>{error}</div>}
    </form>
  );
};

export default DigibeanRedeemForm;

User Registration Form React Component

This is a React component for user registration. It allows users to register with their name, email, or phone number. The component sends a POST request to the backend API to register the user. On successful registration, it triggers the onRegistrationSuccess callback with the user's email or phone number.

The component uses state to manage the input values, loading state, error state, and success state. It includes basic form validation to ensure that the required fields are filled out. The form submission is handled by the handleRegister function, which sends a POST request to the API with the user's registration data. The component also includes error handling to display any error messages to the user.

To use this component, you need to provide the API URL, API key, and a callback function to handle the successful registration. You can customize the component by passing different props to it. The component is designed to be reusable and can be easily integrated into any React application.

Login to your Koffieland account and navigate to the API section to generate your API key. View registration history and other details in the dashboard on Koffieland.


import React, { useState } from 'react';
import { 
  Box, 
  Typography, 
  TextField, 
  Button, 
  Paper, 
  FormControl, 
  FormControlLabel, 
  RadioGroup, 
  Radio,
  Snackbar,
  Alert
} from '@mui/material';
import { registerUser } from './api';

const Registration = ({ onRegistrationSuccess }) => {
  const [registrationType, setRegistrationType] = useState('email');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(false);

  const handleRegistrationTypeChange = (event) => {
    setRegistrationType(event.target.value);
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    
    if (!name) {
      setError('Name is required');
      return;
    }

    if (registrationType === 'email' && !email) {
      setError('Email is required');
      return;
    }

    if (registrationType === 'phone' && !phone) {
      setError('Phone number is required');
      return;
    }

    try {
      setLoading(true);
      setError(null);

      const userData = {
        name,
        shopId: 'kl_m89m0homm64umvzgrqp4sz55qmns2s', // Using API key as shopId
      };

      if (registrationType === 'email') {
        userData.email = email;
      } else {
        userData.phone = phone;
      }

      const response = await registerUser(userData);
      setSuccess(true);
      
      // Pass the registration info back to the parent component
      onRegistrationSuccess(userData.email, userData.phone);
      
      // Reset form
      setName('');
      setEmail('');
      setPhone('');
      setShowForm(false);
    } catch (err) {
      console.error('Registration error:', err);
      setError(
        (err.response && err.response.data && err.response.data.detail) ||
        'Registration failed. Please try again.'
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
      <Typography variant="h5" component="h2" gutterBottom>
        User Registration
      </Typography>
      
      {!showForm ? (
        <Button 
          variant="contained" 
          color="primary" 
          onClick={() => setShowForm(true)}
          fullWidth
        >
          Register to Claim Rewards
        </Button>
      ) : (
        <Box component="form" onSubmit={handleRegister} noValidate>
          <FormControl component="fieldset" sx={{ mb: 2 }}>
            <Typography variant="subtitle1">Register with:</Typography>
            <RadioGroup
              row
              name="registration-type"
              value={registrationType}
              onChange={handleRegistrationTypeChange}
            >
              <FormControlLabel value="email" control={<Radio />} label="Email" />
              <FormControlLabel value="phone" control={<Radio />} label="Phone" />
            </RadioGroup>
          </FormControl>
          
          <TextField
            margin="normal"
            required
            fullWidth
            id="name"
            label="Full Name"
            name="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            autoFocus
          />
          
          {registrationType === 'email' ? (
            <TextField
              margin="normal"
              required
              fullWidth
              id="email"
              label="Email Address"
              name="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          ) : (
            <TextField
              margin="normal"
              required
              fullWidth
              id="phone"
              label="Phone Number"
              name="phone"
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+1234567890"
            />
          )}
          
          <Box sx={{ mt: 2, display: 'flex', gap: 2 }}>
            <Button
              type="submit"
              variant="contained"
              color="primary"
              disabled={loading}
              sx={{ flex: 1 }}
            >
              {loading ? 'Registering...' : 'Register'}
            </Button>
            <Button
              variant="outlined"
              onClick={() => setShowForm(false)}
              sx={{ flex: 1 }}
            >
              Cancel
            </Button>
          </Box>
        </Box>
      )}
      
      <Snackbar 
        open={error !== null} 
        autoHideDuration={6000} 
        onClose={() => setError(null)}
      >
        <Alert onClose={() => setError(null)} severity="error" sx={{ width: '100%' }}>
          {error}
        </Alert>
      </Snackbar>
      
      <Snackbar 
        open={success} 
        autoHideDuration={6000} 
        onClose={() => setSuccess(false)}
      >
        <Alert onClose={() => setSuccess(false)} severity="success" sx={{ width: '100%' }}>
          Registration successful!
        </Alert>
      </Snackbar>
    </Paper>
  );
};

export default Registration;

cURL Examples

Here are some cURL examples for using the Koffieland API. These examples demonstrate how to register a new user, redeem a reward, get remaining beans, and claim beans.


 # 1. Register a new user
curl -X POST http://localhost:8080/register   -H "Content-Type: application/json"   -H "x-api-key: <YOUR_API_KEY>"   -d '{
    "email": "alice@example.com",
    "name": "Alice Example",
    "shopId": "<SHOP_OBJECT_ID>"
  }'
# 2. Redeem a reward
curl -X POST http://localhost:8080/redeem   -H "Content-Type: application/json"   -H "x-api-key: <YOUR_API_KEY>"   -d '{
    "email": "
    "phone": "+1234567890",
    "rewardId": "<REWARD_ID>"
  }'
# 3. Get remaining beans
curl -X GET http://localhost:8080/rewards/remaining   -H "Content-Type: application/json"   -H "x-api-key: <YOUR_API_KEY>"   -d '{
    "email": "
    "phone": "+1234567890"
  }'
# 4. Claim beans
curl -X POST http://localhost:8080/claim   -H "Content-Type: application/json"   -H "x-api
  -d '{
    "email": "
    "phone": "+1234567890",
    "beanCount": 4000,
    "payout": "Free Drink"
  }'

You can use these cURL commands in your terminal to interact with the Koffieland API. Make sure to replace the placeholders with your actual API key and user details.

For more information on the API endpoints and their parameters, please refer to the API documentation.