# FSSAI FoSCoS Scraper (`codingfrontend/fssai-foscos-scraper`) Actor

A robust, high-performance utility designed for developer automation, data integration, and AI training. Features built-in captcha bypass, headful/headless browser execution, and proxy support to scrape FSSAI data seamlessly, reliably, and at scale.

- **URL**: https://apify.com/codingfrontend/fssai-foscos-scraper.md
- **Developed by:** [Coding Frontned](https://apify.com/codingfrontend) (community)
- **Categories:** Automation, Developer tools, Integrations
- **Stats:** 43 total users, 1 monthly users, 100.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

from $4.99 / 1,000 results

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## FSSAI FoSCoS Scraper

An Apify Actor for verifying FSSAI (Food Safety and Standards Authority of India) license numbers using the FoSCoS (Food Safety Compliance System) portal. This scraper uses advanced encryption/decryption techniques to securely communicate with the FSSAI API and extract comprehensive license information.

### Features

- **Advanced Encryption**: Implements AES-ECB encryption with custom key generation for secure API communication
- **Comprehensive License Data**: Extracts complete FSSAI license information including company details, addresses, and license status
- **Robust Error Handling**: Detailed error logging and graceful failure handling
- **Structured JSON Output**: Well-formatted data with proper data types and validation
- **Apify Integration**: Full Apify platform support with dataset storage and logging
- **Detailed Logging**: Saves encrypted requests, API responses, and decrypted data for debugging

### Input Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `fssaiNos` | Array | Yes | `["12421012003663"]` | Array of 14-digit FSSAI license numbers to verify |
| `proxyConfiguration` | Object | No | `{}` | Optional proxy configuration. Example: `{ "useApifyProxy": true, "apifyProxyGroups": ["RESIDENTIAL"], "apifyProxyCountry": "IN" }` — when enabled, the Actor will use Apify Proxy for browser and HTTP requests.

#### Input Schema Example

```json
{
  "fssaiNos": ["12421012003663", "12418012002769"]
}
```

**With Apify Proxy enabled:**

```json
{
  "fssaiNos": ["12421012003663"],
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": ["RESIDENTIAL"],
    "apifyProxyCountry": "IN"
  }
}
```

### Output Schema

The scraper outputs structured JSON data for each FSSAI license verification. Below is the complete output schema:

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `fssai_no` | String | Yes | 14-digit FSSAI license number that was verified |
| `success` | Boolean | Yes | Whether the FSSAI license verification was successful |
| `premiseaddress` | String | No | Registered business address for the FSSAI license |
| `licenseno` | String | No | FSSAI license number (same as fssai\_no) |
| `fboid` | Number | No | Food Business Operator ID |
| `displayrefid` | String | No | Display reference ID for the license |
| `licensecategoryname` | String | No | License category (State License, Central License, etc.) |
| `statename` | String | No | State where the license is registered |
| `statusdesc` | String | No | Current status of the license (License Issued, etc.) |
| `licensecategoryid` | Number | No | Numeric ID for the license category |
| `talukname` | String/Null | No | Taluk or block name where the premises is located |
| `districtname` | String/Null | No | District where the license is registered |
| `companyname` | String/Null | No | Registered company or business name |
| `licenseactiveflag` | Boolean | No | Whether the license is currently active |
| `refid` | Number | No | Internal reference ID |
| `apptypedesc` | String | No | Type of application (Renewal, New, etc.) |
| `villagename` | String/Null | No | Village name (if applicable) |
| `premisepincode` | Number | No | PIN code of the premises |

### Technical Details

#### Encryption Implementation

- **Algorithm**: AES-128-ECB with PKCS7 padding
- **Key Generation**: Custom XOR-based key derivation using predefined arrays
- **Request Encryption**: Plain JSON payloads are encrypted before sending
- **Response Decryption**: Encrypted API responses are decrypted using matching keys
- **Security**: Implements the exact encryption scheme used by FoSCoS portal

#### Data Processing

- **Validation**: 14-digit FSSAI number format validation
- **Error Handling**: Comprehensive error catching with detailed logging
- **Data Extraction**: Automatic parsing of decrypted license information
- **Logging**: Saves all request/response data for debugging

### Sample Output

**Successful Verification:**

```json
{
  "fssai_no": "12421012003663",
  "success": true,
  "premiseaddress": "2-C, Vinayaga Nagar",
  "licenseno": "12421012003663",
  "fboid": 29501920051690868,
  "displayrefid": "20241121106688114",
  "licensecategoryname": "State License",
  "statename": "Tamil Nadu",
  "statusdesc": "License Issued",
  "licensecategoryid": 2,
  "talukname": "Madurai Corporation Ward-44",
  "districtname": "Madurai",
  "companyname": " Sapphire Foods India Limited (KFC) ",
  "licenseactiveflag": true,
  "refid": 106688114,
  "apptypedesc": "Renewal",
  "villagename": null,
  "premisepincode": 625020
}
```

**Failed Verification:**

```json
{
  "fssai_no": "12421012003663",
  "success": false
}
```

### Usage Examples

#### Single License Verification

```json
{
  "fssaiNos": ["12421012003663"]
}
```

#### Multiple License Verification

```json
{
  "fssaiNos": [
    "12421012003663",
    "12418012002769",
    "10011011000123"
  ]
}
```

#### Playwright-based CSRF & cookie fetch (preferred)

The Actor uses Playwright to fetch HTTP-only cookies and the CSRF token from the FoSCoS homepage before making API requests. This mirrors how a real browser obtains and sends the CSRF token and is the only method used by default to obtain the CSRF token (env overrides are still available for debugging).

To enable Playwright, install it in the Actor folder (package.json pins a compatible version):

```bash
npm install --save playwright
```

Or run `npm ci` after pulling the updated `package.json` which includes Playwright as a dependency.

### Error Handling

The scraper handles various error scenarios with intelligent retry logic:

- **Invalid FSSAI Format**: Returns error for non-14-digit numbers
- **API Errors**: Automatic retry with exponential backoff (up to 3 attempts)
- **Network Timeouts**: 45-second timeout with retry mechanism
- **Decryption Failures**: Saves encrypted responses for manual analysis
- **Rate Limiting**: Built-in delays between requests

### Retry Logic

The scraper implements robust retry logic for each FSSAI number:

- **Max Attempts**: 3 attempts per FSSAI number
- **Backoff Strategy**: Exponential backoff (1s → 2s → 4s, capped at 5s)
- **Smart Retries**: Only retries on network/API errors, not validation errors
- **Per-Attempt Logging**: Detailed logs for each retry attempt

### Security Notes

- **Encryption Keys**: Uses the same encryption scheme as the official FoSCoS portal
- **Data Privacy**: All sensitive data is properly encrypted in transit
- **API Compliance**: Follows the official FSSAI API specifications
- **No Data Storage**: Only processes and returns license verification results

### Support

For issues and questions:

- Check the detailed logs in `storage/logs/{fssaiNo}/` directories
- Review the Apify Actor logs in the platform
- Ensure FSSAI numbers are valid 14-digit format
- Verify API connectivity to FoSCoS portal
- Email : lakshmanan.w3dev@gmail.com

# Actor input Schema

## `fssaiNos` (type: `array`):

FSSAI numbers to scrape data

## `headless` (type: `boolean`):

Run browser in headless mode. Set to false to see the browser window (useful for debugging).

## Actor input object example

```json
{
  "fssaiNos": [
    "12421012003663"
  ],
  "headless": true
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "fssaiNos": [
        "12421012003663"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("codingfrontend/fssai-foscos-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "fssaiNos": ["12421012003663"] }

# Run the Actor and wait for it to finish
run = client.actor("codingfrontend/fssai-foscos-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "fssaiNos": [
    "12421012003663"
  ]
}' |
apify call codingfrontend/fssai-foscos-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=codingfrontend/fssai-foscos-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/pTvhH8HWvsTqhdwoA/builds/De6cXZywbdKKdd72d/openapi.json
