API Documentation

Complete guide to SSU Methods Transfer Analysis API

Version 1.0
# Login request
curl -X POST "http://service.ssumethods.com/api/login" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "your_password"
  }'

# Register request
curl -X POST "http://service.ssumethods.com/api/register" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "name": "John Doe",
    "email": "user@example.com",
    "password": "your_password",
    "password_confirmation": "your_password"
  }'
// Login function
const login = async (email, password) => {
  try {
    const response = await fetch('http://service.ssumethods.com/api/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        email: email,
        password: password
      })
    });

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

    const data = await response.json();
    
    // Store the token for future requests
    localStorage.setItem('api_token', data.token);
    
    console.log('Login successful:', data);
    return data;
  } catch (error) {
    console.error('Login error:', error);
    throw error;
  }
};

// Register function
const register = async (name, email, password, passwordConfirmation) => {
  try {
    const response = await fetch('http://service.ssumethods.com/api/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        name: name,
        email: email,
        password: password,
        password_confirmation: passwordConfirmation
      })
    });

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

    const data = await response.json();
    
    // Store the token for future requests
    localStorage.setItem('api_token', data.token);
    
    console.log('Registration successful:', data);
    return data;
  } catch (error) {
    console.error('Registration error:', error);
    throw error;
  }
};

// Usage examples
login('user@example.com', 'password123');
register('John Doe', 'john@example.com', 'password123', 'password123');
import requests
import json
from typing import Dict, Any

class AuthAPI:
    def __init__(self, base_url: str):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        })
    
    def login(self, email: str, password: str) -> Dict[str, Any]:
        """Login user and get access token"""
        try:
            response = self.session.post(
                f'{self.base_url}/api/login',
                json={
                    'email': email,
                    'password': password
                },
                timeout=30
            )
            response.raise_for_status()
            
            data = response.json()
            
            # Store token for future requests
            self.session.headers.update({
                'Authorization': f'Bearer {data["token"]}'
            })
            
            return data
        
        except requests.exceptions.RequestException as e:
            print(f"Login error: {e}")
            raise
    
    def register(self, name: str, email: str, password: str, password_confirmation: str) -> Dict[str, Any]:
        """Register new user"""
        try:
            response = self.session.post(
                f'{self.base_url}/api/register',
                json={
                    'name': name,
                    'email': email,
                    'password': password,
                    'password_confirmation': password_confirmation
                },
                timeout=30
            )
            response.raise_for_status()
            
            data = response.json()
            
            # Store token for future requests
            self.session.headers.update({
                'Authorization': f'Bearer {data["token"]}'
            })
            
            return data
        
        except requests.exceptions.RequestException as e:
            print(f"Registration error: {e}")
            raise

# Usage example
auth = AuthAPI('http://service.ssumethods.com')

try:
    # Login
    login_data = auth.login('user@example.com', 'password123')
    print("Login successful!")
    print(f"User: {login_data['user']['name']}")
    
    # Or register
    # register_data = auth.register('John Doe', 'john@example.com', 'password123', 'password123')
    # print("Registration successful!")
    
except Exception as e:
    print(f"Authentication failed: {e}")
<?php

class AuthAPI {
    private $baseUrl;
    private $token;
    
    public function __construct($baseUrl) {
        $this->baseUrl = rtrim($baseUrl, '/');
    }
    
    public function login($email, $password) {
        $data = [
            'email' => $email,
            'password' => $password
        ];
        
        $response = $this->makeRequest('/api/login', 'POST', $data);
        
        if (isset($response['token'])) {
            $this->token = $response['token'];
        }
        
        return $response;
    }
    
    public function register($name, $email, $password, $passwordConfirmation) {
        $data = [
            'name' => $name,
            'email' => $email,
            'password' => $password,
            'password_confirmation' => $passwordConfirmation
        ];
        
        $response = $this->makeRequest('/api/register', 'POST', $data);
        
        if (isset($response['token'])) {
            $this->token = $response['token'];
        }
        
        return $response;
    }
    
    private function makeRequest($endpoint, $method = 'GET', $data = null) {
        $url = $this->baseUrl . $endpoint;
        
        $headers = [
            'Content-Type: application/json',
            'Accept: application/json'
        ];
        
        if ($this->token) {
            $headers[] = 'Authorization: Bearer ' . $this->token;
        }
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_SSL_VERIFYPEER => false
        ]);
        
        if ($data && in_array($method, ['POST', 'PUT', 'PATCH'])) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new Exception("cURL Error: " . $error);
        }
        
        $decodedResponse = json_decode($response, true);
        
        if ($httpCode >= 400) {
            throw new Exception("HTTP Error $httpCode: " . ($decodedResponse['message'] ?? 'Unknown error'));
        }
        
        return $decodedResponse;
    }
    
    public function getToken() {
        return $this->token;
    }
}

// Usage example
try {
    $auth = new AuthAPI('http://service.ssumethods.com');
    
    // Login
    $loginResponse = $auth->login('user@example.com', 'password123');
    echo "Login successful!\n";
    echo "User: " . $loginResponse['user']['name'] . "\n";
    echo "Token: " . $auth->getToken() . "\n";
    
    // Or register
    // $registerResponse = $auth->register('John Doe', 'john@example.com', 'password123', 'password123');
    // echo "Registration successful!\n";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

?>
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

public class AuthAPI {
    private final String baseUrl;
    private final HttpClient httpClient;
    private final ObjectMapper objectMapper;
    private String token;
    
    public AuthAPI(String baseUrl) {
        this.baseUrl = baseUrl.replaceAll("/$", "");
        this.httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30))
            .build();
        this.objectMapper = new ObjectMapper();
    }
    
    public JsonNode login(String email, String password) throws IOException, InterruptedException {
        String requestBody = String.format(
            "{\"email\":\"%s\",\"password\":\"%s\"}", 
            email, password
        );
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(this.baseUrl + "/api/login"))
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(requestBody))
            .timeout(Duration.ofSeconds(30))
            .build();
        
        HttpResponse<String> response = httpClient.send(
            request, 
            HttpResponse.BodyHandlers.ofString()
        );
        
        if (response.statusCode() != 200) {
            throw new RuntimeException("Login failed with HTTP " + response.statusCode());
        }
        
        JsonNode jsonResponse = objectMapper.readTree(response.body());
        
        // Store token for future requests
        if (jsonResponse.has("token")) {
            this.token = jsonResponse.get("token").asText();
        }
        
        return jsonResponse;
    }
    
    public JsonNode register(String name, String email, String password, String passwordConfirmation) 
            throws IOException, InterruptedException {
        String requestBody = String.format(
            "{\"name\":\"%s\",\"email\":\"%s\",\"password\":\"%s\",\"password_confirmation\":\"%s\"}", 
            name, email, password, passwordConfirmation
        );
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(this.baseUrl + "/api/register"))
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(requestBody))
            .timeout(Duration.ofSeconds(30))
            .build();
        
        HttpResponse<String> response = httpClient.send(
            request, 
            HttpResponse.BodyHandlers.ofString()
        );
        
        if (response.statusCode() != 201) {
            throw new RuntimeException("Registration failed with HTTP " + response.statusCode());
        }
        
        JsonNode jsonResponse = objectMapper.readTree(response.body());
        
        // Store token for future requests
        if (jsonResponse.has("token")) {
            this.token = jsonResponse.get("token").asText();
        }
        
        return jsonResponse;
    }
    
    public String getToken() {
        return this.token;
    }
    
    public static void main(String[] args) {
        try {
            AuthAPI auth = new AuthAPI("http://service.ssumethods.com");
            
            // Login
            JsonNode loginResponse = auth.login("user@example.com", "password123");
            System.out.println("Login successful!");
            System.out.println("User: " + loginResponse.get("user").get("name").asText());
            System.out.println("Token: " + auth.getToken());
            
        } catch (Exception e) {
            System.err.println("Authentication failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"
)

type AuthAPI struct {
    BaseURL string
    Token   string
    Client  *http.Client
}

type LoginRequest struct {
    Email    string `json:"email"`
    Password string `json:"password"`
}

type RegisterRequest struct {
    Name                 string `json:"name"`
    Email                string `json:"email"`
    Password             string `json:"password"`
    PasswordConfirmation string `json:"password_confirmation"`
}

type AuthResponse struct {
    User struct {
        ID    int    `json:"id"`
        Name  string `json:"name"`
        Email string `json:"email"`
    } `json:"user"`
    Token   string `json:"token"`
    Message string `json:"message"`
}

func NewAuthAPI(baseURL string) *AuthAPI {
    return &AuthAPI{
        BaseURL: baseURL,
        Client: &http.Client{
            Timeout: 30 * time.Second,
        },
    }
}

func (api *AuthAPI) Login(email, password string) (*AuthResponse, error) {
    loginReq := LoginRequest{
        Email:    email,
        Password: password,
    }
    
    jsonData, err := json.Marshal(loginReq)
    if err != nil {
        return nil, fmt.Errorf("marshaling request: %w", err)
    }
    
    req, err := http.NewRequest("POST", api.BaseURL+"/api/login", bytes.NewBuffer(jsonData))
    if err != nil {
        return nil, fmt.Errorf("creating request: %w", err)
    }
    
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Accept", "application/json")
    
    resp, err := api.Client.Do(req)
    if err != nil {
        return nil, fmt.Errorf("making request: %w", err)
    }
    defer resp.Body.Close()
    
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, fmt.Errorf("reading response: %w", err)
    }
    
    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("login failed with status %d: %s", resp.StatusCode, string(body))
    }
    
    var authResp AuthResponse
    if err := json.Unmarshal(body, &authResp); err != nil {
        return nil, fmt.Errorf("parsing response: %w", err)
    }
    
    // Store token for future requests
    api.Token = authResp.Token
    
    return &authResp, nil
}

func (api *AuthAPI) Register(name, email, password, passwordConfirmation string) (*AuthResponse, error) {
    registerReq := RegisterRequest{
        Name:                 name,
        Email:                email,
        Password:             password,
        PasswordConfirmation: passwordConfirmation,
    }
    
    jsonData, err := json.Marshal(registerReq)
    if err != nil {
        return nil, fmt.Errorf("marshaling request: %w", err)
    }
    
    req, err := http.NewRequest("POST", api.BaseURL+"/api/register", bytes.NewBuffer(jsonData))
    if err != nil {
        return nil, fmt.Errorf("creating request: %w", err)
    }
    
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Accept", "application/json")
    
    resp, err := api.Client.Do(req)
    if err != nil {
        return nil, fmt.Errorf("making request: %w", err)
    }
    defer resp.Body.Close()
    
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, fmt.Errorf("reading response: %w", err)
    }
    
    if resp.StatusCode != http.StatusCreated {
        return nil, fmt.Errorf("registration failed with status %d: %s", resp.StatusCode, string(body))
    }
    
    var authResp AuthResponse
    if err := json.Unmarshal(body, &authResp); err != nil {
        return nil, fmt.Errorf("parsing response: %w", err)
    }
    
    // Store token for future requests
    api.Token = authResp.Token
    
    return &authResp, nil
}

func main() {
    auth := NewAuthAPI("http://service.ssumethods.com")
    
    // Login example
    loginResp, err := auth.Login("user@example.com", "password123")
    if err != nil {
        fmt.Printf("Login error: %v\n", err)
        return
    }
    
    fmt.Println("Login successful!")
    fmt.Printf("User: %s\n", loginResp.User.Name)
    fmt.Printf("Token: %s\n", auth.Token)
}