# Blog API Documentation

This document describes the Blog Management APIs for both admin and public endpoints. Blogs are articles that can be published and viewed by the public.

---

## Table of Contents

1. [Admin Blog Management APIs](#admin-blog-management-apis)
   - [Get All Blogs](#get-all-blogs)
   - [Get Single Blog](#get-single-blog)
   - [Add New Blog](#add-new-blog)
   - [Update Blog](#update-blog)
   - [Delete Blog](#delete-blog)
2. [Public Blog APIs](#public-blog-apis)
   - [Get All Published Blogs](#get-all-published-blogs)
   - [Get Single Published Blog](#get-single-published-blog)
   - [Get Blog by Slug](#get-blog-by-slug)
   - [Get Latest Blogs](#get-latest-blogs)

---

## Admin Blog Management APIs

All admin endpoints require authentication using a Bearer token in the Authorization header.

**Base URL:** `/api/admin/blog`

**Authentication:** Required (Admin Bearer Token)

---

### Get All Blogs

Get a list of all blogs (both published and unpublished) with admin details.

**Endpoint:** `GET /api/admin/blog`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "title": "How to Use Digital Seva Services",
            "slug": "how-to-use-digital-seva-services",
            "excerpt": "Learn how to use our digital services platform effectively.",
            "content": "Full blog content here...",
            "featured_image": "https://example.com/blog-image.jpg",
            "meta_title": "How to Use Digital Seva Services",
            "meta_description": "Complete guide on using Digital Seva platform",
            "is_published": true,
            "published_at": "2025-12-06T14:44:00.000000Z",
            "views": 150,
            "created_by": 1,
            "created_at": "2025-12-06T14:44:00.000000Z",
            "updated_at": "2025-12-06T14:44:00.000000Z",
            "admin": {
                "id": 1,
                "username": "admin",
                "email": "admin@alldigtalseva.com"
            }
        }
    ]
}
```

**Error Response (401) - Unauthorized:**
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/blog" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Accept: application/json"
```

---

### Get Single Blog

Get details of a specific blog by ID.

**Endpoint:** `GET /api/admin/blog/{id}`

**URL Parameters:**
- `id` (required, integer): Blog ID

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "title": "How to Use Digital Seva Services",
        "slug": "how-to-use-digital-seva-services",
        "excerpt": "Learn how to use our digital services platform effectively.",
        "content": "Full blog content here...",
        "featured_image": "https://example.com/blog-image.jpg",
        "meta_title": "How to Use Digital Seva Services",
        "meta_description": "Complete guide on using Digital Seva platform",
        "is_published": true,
        "published_at": "2025-12-06T14:44:00.000000Z",
        "views": 150,
        "created_by": 1,
        "created_at": "2025-12-06T14:44:00.000000Z",
        "updated_at": "2025-12-06T14:44:00.000000Z",
        "admin": {
            "id": 1,
            "username": "admin",
            "email": "admin@alldigtalseva.com"
        }
    }
}
```

**Error Response (404) - Not Found:**
```json
{
    "success": false,
    "message": "Blog not found"
}
```

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/blog/1" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Accept: application/json"
```

---

### Add New Blog

Create a new blog post.

**Endpoint:** `POST /api/admin/blog`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "title": "How to Use Digital Seva Services",
    "slug": "how-to-use-digital-seva-services",
    "excerpt": "Learn how to use our digital services platform effectively.",
    "content": "Full blog content here. This can be HTML or plain text...",
    "featured_image": "https://example.com/blog-image.jpg",
    "meta_title": "How to Use Digital Seva Services",
    "meta_description": "Complete guide on using Digital Seva platform",
    "is_published": true,
    "published_at": "2025-12-06 14:44:00"
}
```

**Field Descriptions:**
- `title` (required, string, max 255): Blog title
- `slug` (optional, string, max 255, unique): URL-friendly slug (auto-generated from title if not provided)
- `excerpt` (optional, string, max 500): Short description/summary of the blog
- `content` (required, string): Full blog content (can be HTML or plain text)
- `featured_image` (optional, string, URL): Featured image URL
- `meta_title` (optional, string, max 255): SEO meta title
- `meta_description` (optional, string, max 500): SEO meta description
- `is_published` (optional, boolean): Whether blog is published (default: false)
- `published_at` (optional, date): Publication date (auto-set to now if is_published is true)

**Success Response (201):**
```json
{
    "success": true,
    "message": "Blog created successfully",
    "data": {
        "id": 1,
        "title": "How to Use Digital Seva Services",
        "slug": "how-to-use-digital-seva-services",
        "excerpt": "Learn how to use our digital services platform effectively.",
        "content": "Full blog content here...",
        "featured_image": "https://example.com/blog-image.jpg",
        "meta_title": "How to Use Digital Seva Services",
        "meta_description": "Complete guide on using Digital Seva platform",
        "is_published": true,
        "published_at": "2025-12-06T14:44:00.000000Z",
        "views": 0,
        "created_by": 1,
        "created_at": "2025-12-06T14:44:00.000000Z",
        "updated_at": "2025-12-06T14:44:00.000000Z",
        "admin": {
            "id": 1,
            "username": "admin",
            "email": "admin@alldigtalseva.com"
        }
    }
}
```

**Error Response (422) - Validation Error:**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "title": [
            "The title field is required."
        ],
        "content": [
            "The content field is required."
        ],
        "slug": [
            "The slug has already been taken."
        ]
    }
}
```

**cURL Example:**
```bash
curl -X POST "https://api.alldigtalseva.com/api/admin/blog" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "title": "How to Use Digital Seva Services",
    "excerpt": "Learn how to use our digital services platform effectively.",
    "content": "Full blog content here. This can be HTML or plain text...",
    "featured_image": "https://example.com/blog-image.jpg",
    "is_published": true
  }'
```

**Note:** If `slug` is not provided, it will be automatically generated from the `title`.

---

### Update Blog

Update an existing blog post.

**Endpoint:** `PUT /api/admin/blog/{id}` or `PATCH /api/admin/blog/{id}`

**URL Parameters:**
- `id` (required, integer): Blog ID

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "title": "Updated Blog Title",
    "content": "Updated content...",
    "is_published": false
}
```

**Field Descriptions:**
- All fields are optional (use `PUT` for full update, `PATCH` for partial update)
- Same validation rules as Add New Blog
- If `title` is updated and `slug` is not provided, a new slug will be generated

**Success Response (200):**
```json
{
    "success": true,
    "message": "Blog updated successfully",
    "data": {
        "id": 1,
        "title": "Updated Blog Title",
        "slug": "updated-blog-title",
        "content": "Updated content...",
        "is_published": false,
        ...
    }
}
```

**Error Response (404) - Not Found:**
```json
{
    "success": false,
    "message": "Blog not found"
}
```

**cURL Example:**
```bash
curl -X PUT "https://api.alldigtalseva.com/api/admin/blog/1" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "title": "Updated Blog Title",
    "content": "Updated content...",
    "is_published": false
  }'
```

---

### Delete Blog

Delete a blog post.

**Endpoint:** `DELETE /api/admin/blog/{id}`

**URL Parameters:**
- `id` (required, integer): Blog ID

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "message": "Blog deleted successfully"
}
```

**Error Response (404) - Not Found:**
```json
{
    "success": false,
    "message": "Blog not found"
}
```

**cURL Example:**
```bash
curl -X DELETE "https://api.alldigtalseva.com/api/admin/blog/1" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Accept: application/json"
```

---

## Public Blog APIs

Public endpoints for viewing published blogs. No authentication required.

**Base URL:** `/api/blog`

**Authentication:** Not required

---

### Get All Published Blogs

Get all published blogs with pagination. Only blogs that are published and have a published_at date in the past are returned.

**Endpoint:** `GET /api/blog`

**Query Parameters:**
- `per_page` (optional, integer, 1-50): Number of blogs per page (default: 10)

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "title": "How to Use Digital Seva Services",
            "slug": "how-to-use-digital-seva-services",
            "excerpt": "Learn how to use our digital services platform effectively.",
            "featured_image": "https://example.com/blog-image.jpg",
            "published_at": "2025-12-06T14:44:00.000000Z",
            "views": 150,
            "created_at": "2025-12-06T14:44:00.000000Z"
        },
        {
            "id": 2,
            "title": "Understanding Digital Services",
            "slug": "understanding-digital-services",
            "excerpt": "A comprehensive guide to digital services.",
            "featured_image": "https://example.com/blog-image2.jpg",
            "published_at": "2025-12-05T10:00:00.000000Z",
            "views": 89,
            "created_at": "2025-12-05T10:00:00.000000Z"
        }
    ],
    "pagination": {
        "current_page": 1,
        "last_page": 3,
        "per_page": 10,
        "total": 25,
        "from": 1,
        "to": 10
    }
}
```

**Note:** Blogs are ordered by `published_at` date (newest first). Only published blogs with `published_at <= now()` are returned.

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/blog?per_page=10" \
  -H "Accept: application/json"
```

**JavaScript/Fetch Example:**
```javascript
async function loadBlogs(page = 1, perPage = 10) {
  try {
    const response = await fetch(`https://api.alldigtalseva.com/api/blog?per_page=${perPage}&page=${page}`);
    const result = await response.json();
    
    if (result.success) {
      console.log('Blogs:', result.data);
      console.log('Pagination:', result.pagination);
      // Display blogs
    }
  } catch (error) {
    console.error('Failed to load blogs:', error);
  }
}
```

---

### Get Single Published Blog

Get full details of a specific published blog by ID. View count is automatically incremented.

**Endpoint:** `GET /api/blog/{id}`

**URL Parameters:**
- `id` (required, integer): Blog ID

**Success Response (200):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "title": "How to Use Digital Seva Services",
        "slug": "how-to-use-digital-seva-services",
        "excerpt": "Learn how to use our digital services platform effectively.",
        "content": "Full blog content here. This can be HTML or plain text...",
        "featured_image": "https://example.com/blog-image.jpg",
        "meta_title": "How to Use Digital Seva Services",
        "meta_description": "Complete guide on using Digital Seva platform",
        "is_published": true,
        "published_at": "2025-12-06T14:44:00.000000Z",
        "views": 151,
        "created_at": "2025-12-06T14:44:00.000000Z",
        "updated_at": "2025-12-06T14:44:00.000000Z",
        "admin": {
            "id": 1,
            "username": "admin",
            "email": "admin@alldigtalseva.com"
        }
    }
}
```

**Error Response (404) - Not Found or Not Published:**
```json
{
    "success": false,
    "message": "Blog not found or not published"
}
```

**Note:** View count is automatically incremented when a blog is viewed.

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/blog/1" \
  -H "Accept: application/json"
```

---

### Get Blog by Slug

Get full details of a specific published blog by slug (SEO-friendly URL). View count is automatically incremented.

**Endpoint:** `GET /api/blog/slug/{slug}`

**URL Parameters:**
- `slug` (required, string): Blog slug (e.g., "how-to-use-digital-seva-services")

**Success Response (200):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "title": "How to Use Digital Seva Services",
        "slug": "how-to-use-digital-seva-services",
        "excerpt": "Learn how to use our digital services platform effectively.",
        "content": "Full blog content here. This can be HTML or plain text...",
        "featured_image": "https://example.com/blog-image.jpg",
        "meta_title": "How to Use Digital Seva Services",
        "meta_description": "Complete guide on using Digital Seva platform",
        "is_published": true,
        "published_at": "2025-12-06T14:44:00.000000Z",
        "views": 152,
        "created_at": "2025-12-06T14:44:00.000000Z",
        "updated_at": "2025-12-06T14:44:00.000000Z",
        "admin": {
            "id": 1,
            "username": "admin",
            "email": "admin@alldigtalseva.com"
        }
    }
}
```

**Error Response (404) - Not Found or Not Published:**
```json
{
    "success": false,
    "message": "Blog not found or not published"
}
```

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/blog/slug/how-to-use-digital-seva-services" \
  -H "Accept: application/json"
```

**Note:** This endpoint is more SEO-friendly as it uses slugs instead of IDs in the URL.

---

### Get Latest Blogs

Get the most recent published blogs. Useful for displaying "Latest Posts" section.

**Endpoint:** `GET /api/blog/latest`

**Query Parameters:**
- `limit` (optional, integer, 1-20): Number of blogs to return (default: 5)

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "title": "How to Use Digital Seva Services",
            "slug": "how-to-use-digital-seva-services",
            "excerpt": "Learn how to use our digital services platform effectively.",
            "featured_image": "https://example.com/blog-image.jpg",
            "published_at": "2025-12-06T14:44:00.000000Z",
            "views": 150,
            "created_at": "2025-12-06T14:44:00.000000Z"
        },
        {
            "id": 2,
            "title": "Understanding Digital Services",
            "slug": "understanding-digital-services",
            "excerpt": "A comprehensive guide to digital services.",
            "featured_image": "https://example.com/blog-image2.jpg",
            "published_at": "2025-12-05T10:00:00.000000Z",
            "views": 89,
            "created_at": "2025-12-05T10:00:00.000000Z"
        }
    ]
}
```

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/blog/latest?limit=5" \
  -H "Accept: application/json"
```

**JavaScript/Fetch Example:**
```javascript
async function loadLatestBlogs() {
  try {
    const response = await fetch('https://api.alldigtalseva.com/api/blog/latest?limit=5');
    const result = await response.json();
    
    if (result.success) {
      console.log('Latest blogs:', result.data);
      // Display in "Latest Posts" section
    }
  } catch (error) {
    console.error('Failed to load latest blogs:', error);
  }
}
```

---

## Integration Notes

### For Frontend Integration

1. **Display Blog List:**
   ```javascript
   // Angular/React/Vue example
   async function loadBlogs(page = 1) {
     try {
       const response = await fetch(`https://api.alldigtalseva.com/api/blog?per_page=10&page=${page}`);
       const result = await response.json();
       
       if (result.success) {
         // result.data contains array of published blogs
         displayBlogs(result.data);
         // result.pagination contains pagination info
         setupPagination(result.pagination);
       }
     } catch (error) {
       console.error('Failed to load blogs:', error);
     }
   }
   ```

2. **Display Single Blog:**
   ```javascript
   // Using slug (SEO-friendly)
   async function loadBlogBySlug(slug) {
     try {
       const response = await fetch(`https://api.alldigtalseva.com/api/blog/slug/${slug}`);
       const result = await response.json();
       
       if (result.success) {
         // result.data contains full blog details
         displayBlog(result.data);
       }
     } catch (error) {
       console.error('Failed to load blog:', error);
     }
   }
   ```

3. **Display Latest Blogs:**
   ```javascript
   async function loadLatestBlogs() {
     try {
       const response = await fetch('https://api.alldigtalseva.com/api/blog/latest?limit=5');
       const result = await response.json();
       
       if (result.success) {
         // Display in sidebar or homepage
         displayLatestBlogs(result.data);
       }
     } catch (error) {
       console.error('Failed to load latest blogs:', error);
     }
   }
   ```

### SEO Best Practices

1. **Use Slugs for URLs:**
   - Use `/api/blog/slug/{slug}` for SEO-friendly URLs
   - Slugs are automatically generated from titles if not provided

2. **Meta Tags:**
   - Use `meta_title` and `meta_description` for SEO
   - If not provided, use `title` and `excerpt` as fallbacks

3. **Featured Images:**
   - Always include `featured_image` for better social media sharing
   - Use optimized images (recommended: 1200x630 for social sharing)

4. **Content Formatting:**
   - Blog content can be HTML or plain text
   - Use proper heading tags (h1, h2, h3) for better SEO

### Best Practices

1. **Publishing Workflow:**
   - Create blog as draft (`is_published: false`)
   - Review and edit
   - Set `is_published: true` and `published_at` when ready
   - System automatically filters by published status

2. **Slug Management:**
   - Slugs are auto-generated from titles
   - Ensure titles are unique to avoid duplicate slugs
   - Slugs are URL-friendly (lowercase, hyphens instead of spaces)

3. **View Tracking:**
   - View count is automatically incremented on each view
   - Useful for analytics and popular posts

4. **Content Management:**
   - Use `excerpt` for blog list previews
   - Use `content` for full blog display
   - Keep excerpts short (recommended: 150-200 characters)

---

## Error Codes

| Status Code | Description |
|------------|-------------|
| 200 | Success |
| 201 | Created successfully |
| 400 | Bad request |
| 401 | Unauthorized (Admin token required) |
| 404 | Resource not found |
| 422 | Validation error |

---

## Support

For issues or questions regarding the Blog API, please contact the development team.

