Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.
Articles

How to book an IRCTC ticket via the API (with Sample Program)

To book an IRCTC ticket via the API, you’ll need to follow these steps:



### Step 1: Obtain API Access from IRCTC
IRCTC provides its APIs through the Indian Railways Catering and Tourism Corporation (IRCTC) or authorized third-party service providers. You must apply for access and follow their compliance guidelines. Contact IRCTC or visit their developer portal for API access.

### Step 2: Set Up Required APIs
Once access is granted, use the following APIs as part of the ticket booking process:
1. **Authentication API:** Authenticate users and generate a session token.
2. **Train Information API:** Get train schedules, availability, and fare details.
3. **Passenger Reservation API:** Reserve a seat or book a ticket.
4. **Payment API:** Complete the payment through secure channels.

### Step 3: Authenticate and Obtain Session Token
Using your API key and user credentials, authenticate the user to obtain a session token. This token is used in each API call to confirm authorization.

### Step 4: Check Train Availability
Use the Train Information API to check seat availability on the desired train and class for the journey date. You’ll need details like:
   - Train number
   - Date of travel
   - Class and quota (e.g., General, Ladies, etc.)
   - Source and destination stations

### Step 5: Fare Enquiry (Optional)
You may also check the fare for the chosen train and class, helping users confirm the ticket price before booking.

### Step 6: Book the Ticket
Use the Passenger Reservation API, passing in required details like:
   - Passenger information (name, age, gender, etc.)
   - Train number, date, source, and destination
   - Class and quota
   - Session token from authentication

### Step 7: Make Payment
Redirect to the Payment API or use an authorized payment gateway to process the payment. Only upon successful payment will the ticket be confirmed.

### Step 8: Confirm Booking and Retrieve PNR
Upon successful booking, retrieve the Passenger Name Record (PNR) number. Use this to access ticket details, check status, or make cancellations.

### Important Notes:
- **Compliance and Restrictions:** Booking APIs are strictly regulated by IRCTC. Make sure to comply with IRCTC’s terms of use.
- **Third-party Integration:** Some authorized third-party vendors, like RailYatri and ConfirmTkt, offer easier access to these APIs for developers.
- **Use Case Approval:** IRCTC restricts ticket bookings via API to avoid misuse. Ensure your application or platform is authorized for the intended use. 

Here's a simplified example of a program to book an IRCTC ticket via API, assuming you've obtained valid access credentials, including the API key, user token, and other necessary permissions. This example uses Python, showcasing the structure of requests typically made in the IRCTC booking process.

**Note**: This example only simulates the booking process and does not include a real API endpoint for IRCTC, as it requires official authorization and compliance.

### Sample Program to Book a Ticket via IRCTC API

```python
import requests
import json

# Constants for API endpoints (for illustration only)
BASE_URL = "https://api.irctc.co.in"
AUTH_URL = f"{BASE_URL}/auth"
CHECK_AVAILABILITY_URL = f"{BASE_URL}/check-availability"
BOOK_TICKET_URL = f"{BASE_URL}/book-ticket"
PAYMENT_URL = f"{BASE_URL}/payment"

# IRCTC API Credentials
API_KEY = "YOUR_API_KEY"
USERNAME = "YOUR_USERNAME"
PASSWORD = "YOUR_PASSWORD"

# Step 1: Authenticate and Get Session Token
def authenticate():
    headers = {
        "Content-Type": "application/json",
        "X-Api-Key": API_KEY
    }
    data = {
        "username": USERNAME,
        "password": PASSWORD
    }
    
    response = requests.post(AUTH_URL, headers=headers, json=data)
    if response.status_code == 200:
        session_token = response.json().get("session_token")
        print("Authentication successful.")
        return session_token
    else:
        print("Authentication failed:", response.json())
        return None

# Step 2: Check Train Availability
def check_availability(session_token, train_no, travel_date, source, destination, travel_class, quota):
    headers = {
        "Authorization": f"Bearer {session_token}",
        "X-Api-Key": API_KEY
    }
    data = {
        "train_no": train_no,
        "date": travel_date,
        "source": source,
        "destination": destination,
        "class": travel_class,
        "quota": quota
    }
    
    response = requests.post(CHECK_AVAILABILITY_URL, headers=headers, json=data)
    if response.status_code == 200:
        availability = response.json().get("availability")
        print("Train availability checked:", availability)
        return availability
    else:
        print("Availability check failed:", response.json())
        return None

# Step 3: Book Ticket
def book_ticket(session_token, passenger_info, train_no, travel_date, source, destination, travel_class, quota):
    headers = {
        "Authorization": f"Bearer {session_token}",
        "X-Api-Key": API_KEY
    }
    data = {
        "train_no": train_no,
        "date": travel_date,
        "source": source,
        "destination": destination,
        "class": travel_class,
        "quota": quota,
        "passenger_info": passenger_info
    }
    
    response = requests.post(BOOK_TICKET_URL, headers=headers, json=data)
    if response.status_code == 200:
        booking_details = response.json()
        print("Ticket booked successfully:", booking_details)
        return booking_details
    else:
        print("Ticket booking failed:", response.json())
        return None

# Step 4: Make Payment (Simulated)
def make_payment(session_token, booking_id, amount):
    headers = {
        "Authorization": f"Bearer {session_token}",
        "X-Api-Key": API_KEY
    }
    data = {
        "booking_id": booking_id,
        "amount": amount,
        "payment_method": "card"
    }
    
    response = requests.post(PAYMENT_URL, headers=headers, json=data)
    if response.status_code == 200:
        payment_status = response.json().get("status")
        print("Payment successful:", payment_status)
        return payment_status
    else:
        print("Payment failed:", response.json())
        return None

# Example Usage
def main():
    # Authentication
    session_token = authenticate()
    if not session_token:
        return

    # Train availability check
    availability = check_availability(
        session_token,
        train_no="12345",
        travel_date="2024-11-15",
        source="NDLS",
        destination="BCT",
        travel_class="3A",
        quota="GN"
    )
    if not availability:
        return

    # Book the ticket
    passenger_info = [
        {"name": "John Doe", "age": 30, "gender": "M"},
        {"name": "Jane Doe", "age": 28, "gender": "F"}
    ]
    booking_details = book_ticket(
        session_token,
        passenger_info,
        train_no="12345",
        travel_date="2024-11-15",
        source="NDLS",
        destination="BCT",
        travel_class="3A",
        quota="GN"
    )
    if not booking_details:
        return

    # Make Payment
    payment_status = make_payment(session_token, booking_id=booking_details["booking_id"], amount=booking_details["fare"])
    if payment_status == "success":
        print("Booking confirmed! PNR:", booking_details["pnr"])
    else:
        print("Booking failed during payment.")

# Run the program
if __name__ == "__main__":
    main()
```

### Important Notes:
- **Replace placeholders** like `YOUR_API_KEY`, `YOUR_USERNAME`, `YOUR_PASSWORD`, and actual train details.
- **Error handling**: Implement robust error handling, especially for API responses and network issues.
- **Secure sensitive data**: Use secure methods to handle sensitive credentials and tokens.
- **IRCTC Restrictions**: Ensure compliance with IRCTC’s terms of use. Unauthorized or misconfigured use of their API may lead to suspension.

This example demonstrates the general flow but requires actual IRCTC API access, which may have additional specific parameters and headers.

caa November 06 2024 29 reads 0 comments Print

0 comments

Leave a Comment

Please Login to Post a Comment.
  • No Comments have been Posted.

Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 3
Members Online 0

Total Members: 11
Newest Member: Jhilam