Publish Blog Posts via API: REST, GraphQL, and MCP Methods Compared

Why publish blog posts via API

Publishing through a web editor works for occasional posts. But when you need to publish at scale, integrate with other systems, or automate workflows, the API is the only path that scales.

Common API publishing scenarios:

  • CI/CD publishing: Push Markdown to a Git repository, CI pipeline converts and publishes through the API
  • Content syndication: Publish the same content to multiple blogs or platforms automatically
  • Migration scripts: Import hundreds of posts from one platform to another
  • Scheduled content: Use cron jobs or serverless functions to publish at specific times
  • AI-generated content: AI assistants draft content and publish through API without human copy-pasting
  • Dashboard integrations: Custom editorial dashboards that publish through platform APIs

This guide covers API publishing on the major platforms with working code examples. For the broader automation picture, see the automated blog publishing guide .

Architecture diagram showing different API publishing methods: REST, GraphQL, and MCP, with arrows connecting content sources to blog platforms
API publishing methods overview

API publishing on Modern Blogging

Modern Blogging's REST API supports full CRUD operations on posts, pages, images, and settings. Authentication uses API keys — no OAuth complexity.

Authentication

Generate an API key in Dashboard → Settings → API Keys. The key authenticates all requests:

bash
curl -X POST https://yourblog.modernblogging.net/api/posts \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "My API-Published Post",
    "body": "Post content in Markdown or HTML",
    "slug": "my-api-post",
    "status": "published"
  }'

Creating a post

javascript
const response = await fetch('https://yourblog.modernblogging.net/api/posts', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    title: 'TypeScript Generics Explained',
    body: '## Introduction\n\nGenerics allow you to write...',
    slug: 'typescript-generics-explained',
    categories: ['typescript', 'tutorials'],
    status: 'published',
    seo: {
      metaTitle: 'TypeScript Generics Explained — Practical Guide',
      metaDescription: 'Learn TypeScript generics with practical examples...',
      focusKeyword: 'typescript generics',
    },
  }),
})

const post = await response.json()
console.log('Published:', post.slug)

Uploading images

Images can be uploaded separately and referenced in posts:

javascript
const formData = new FormData()
formData.append('file', fs.createReadStream('diagram.png'))
formData.append('alt', 'Architecture diagram showing data flow')

const imgResponse = await fetch('https://yourblog.modernblogging.net/api/images', {
  method: 'POST',
  headers: { 'Authorization': 'Bearer YOUR_API_KEY' },
  body: formData,
})

const image = await imgResponse.json()
// Use image.url in your post body

Publishing via MCP

MCP (Model Context Protocol) lets AI assistants publish posts through natural conversation. The 32 MCP tools include:

  • create_post: Create a new post with title, body, slug, SEO metadata, and categories
  • update_post: Edit an existing post's content or metadata
  • publish_post: Change a draft to published status
  • check_seo: Score a post for SEO quality before publishing
  • upload_image: Upload images for use in posts

In practice, an AI assistant connected via MCP can "Write a 1,500-word post about React server components, optimize it for SEO, and publish it" — executing the actual API calls without human intervention. See MCP tools for developers for the full tool catalog.

Code snippet comparison showing API publishing syntax across four platforms: Modern Blogging REST, Ghost Admin API, WordPress REST, and Hashnode GraphQL
API publishing code comparison

API publishing on Ghost

Ghost provides two APIs: the Content API (read-only, public) and the Admin API (write, authenticated). Publishing requires the Admin API.

Authentication

Ghost uses JWT (JSON Web Tokens) with a custom Admin API key:

javascript
const jwt = require('jsonwebtoken')

const [id, secret] = GHOST_ADMIN_KEY.split(':')
const token = jwt.sign({}, Buffer.from(secret, 'hex'), {
  keyid: id,
  algorithm: 'HS256',
  expiresIn: '5m',
  audience: '/admin/',
})

const response = await fetch('https://yourblog.com/ghost/api/admin/posts/', {
  method: 'POST',
  headers: {
    'Authorization': `Ghost ${token}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    posts: [{
      title: 'My Ghost Post',
      html: '<p>Post content in HTML</p>',
      status: 'published',
    }],
  }),
})

Note: Ghost's JWT authentication is more complex than API key authentication. The key must be split, the secret must be hex-decoded, and tokens expire. For comparison, Modern Blogging uses a simple Bearer token.

API publishing on WordPress

WordPress REST API supports post creation with application passwords (since WordPress 5.6):

bash
curl -X POST https://yourblog.com/wp-json/wp/v2/posts \
  -u "username:APPLICATION_PASSWORD" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "My WordPress Post",
    "content": "<p>Post content in HTML</p>",
    "status": "publish",
    "categories": [5, 12]
  }'

WordPress requires HTML content (not Markdown), uses numeric category IDs, and has verbose response objects. For the full WordPress API limitations, see the WordPress alternative comparison .

API publishing on Hashnode

Hashnode uses a GraphQL API:

javascript
const mutation = `
  mutation PublishPost($input: PublishPostInput!) {
    publishPost(input: $input) {
      post { id title slug }
    }
  }
`

const response = await fetch('https://gql.hashnode.com', {
  method: 'POST',
  headers: {
    'Authorization': HASHNODE_TOKEN,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    query: mutation,
    variables: {
      input: {
        title: 'My Hashnode Post',
        contentMarkdown: '## Hello\n\nPost content in Markdown',
        publicationId: YOUR_PUB_ID,
        tags: [{ slug: 'javascript', name: 'JavaScript' }],
      },
    },
  }),
})

Platform API comparison

Feature

Modern Blogging

Ghost

WordPress

Hashnode

API style

REST

REST

REST

GraphQL

Auth method

API key (Bearer)

JWT (complex)

Application password

Personal token

Content format

Markdown, HTML, Portable Text

HTML, Mobiledoc

HTML

Markdown

Image upload

✅ Separate endpoint

✅ Separate endpoint

✅ Media endpoint

✅ Presigned URL

SEO fields

✅ Built-in

❌ Meta only

✅ Yoast plugin

✅ Basic

MCP integration

✅ 32 tools

❌

❌

❌

Bulk operations

✅

❌

✅

❌

Webhooks

✅

✅

✅ Plugin

✅

Rate limits

Generous

100/min

Varies

100/min

Error messages

Structured JSON

JSON

JSON (verbose)

GraphQL errors

Choosing the right API approach

The best API approach depends on your publishing workflow and technical context. REST APIs are the most straightforward — standard HTTP methods, JSON payloads, and predictable URL patterns. Most developers can write a REST client in any language in under an hour.

GraphQL offers more flexibility for complex queries but adds overhead for simple CRUD operations. If you just need to create a post with a title, body, and metadata, GraphQL's query syntax is more complex than necessary. Hashnode uses GraphQL; Modern Blogging , Ghost, and WordPress use REST.

MCP is the newest approach and fundamentally different. Instead of writing HTTP requests, you describe actions in natural language and an AI assistant executes the API calls. This is not just a convenience layer — it changes who can publish programmatically. A marketing team member who cannot write curl commands can publish through an AI assistant connected via MCP.

For most automation workflows, REST is the right default. Use MCP when AI assistants are part of the publishing pipeline. Use GraphQL only if your platform requires it (Hashnode) or if you need complex queries that fetch data across multiple resources in a single request.

Content format conversion

Different platforms accept different content formats, and converting between them is a common pain point in API publishing workflows.

Markdown is the most portable format. It converts reliably to HTML (using libraries like marked, remark, or markdown-it), and most platforms accept either Markdown or HTML. If your content pipeline involves multiple platforms, write in Markdown and convert at publish time.

Portable Text (used by Modern Blogging and Sanity) is a structured JSON format. Each element — paragraph, heading, image, table, code block — is a typed JSON object. This structure makes content queryable, transformable, and renderable in any context. Converting from Markdown to Portable Text is straightforward with available libraries.

HTML is the least portable format despite being universal. HTML carries rendering assumptions — styles, classes, layout — that may not translate across platforms. If you must work with HTML, strip it to semantic elements before sending to an API.

Modern Blogging accepts all three formats through its API: Markdown for simplicity, HTML for compatibility, and Portable Text for maximum control. The programmatic publishing guide covers the conversion details.

Building a publishing pipeline

A complete API publishing pipeline typically includes these stages. For the full automation guide, see automated blog publishing :

  1. Content source: Markdown files in Git, CMS drafts, AI-generated content, or database records
  2. Transformation: Convert content format (Markdown → HTML → Portable Text), resize images, generate SEO metadata
  3. Validation: Check required fields (title, slug, categories), verify image URLs resolve, run SEO scoring
  4. Publishing: POST to the platform API, handle errors and retries
  5. Verification: Confirm the post is live (GET the published URL), check redirects, validate meta tags
  6. Notification: Alert the team (Slack, email) on success or failure

Batch publishing and migrations

API publishing is most powerful when handling content at scale. Migrating hundreds of posts from one platform to another, publishing a backlog of drafted content, or syndicating content across multiple blogs — these are batch operations that manual publishing cannot handle.

The pattern for batch publishing is straightforward: read content from the source (files, database, or API), transform to the target format, publish through the API with error handling, and verify each published post. Rate limits are the main constraint — most platforms limit API calls to prevent abuse.

Modern Blogging's API handles batch operations efficiently. The rate limits are generous, image uploads are asynchronous (the API returns immediately while the image processes on CDN), and the response includes the published URL for immediate verification. For large migrations, the WordPress import tool handles the entire process automatically.

For custom migration scripts, the pattern looks like this: fetch all source posts, filter to published status, transform content format, upload images and map old URLs to new CDN URLs, replace image references in content, publish each post with original dates preserved, and create redirects from old URLs to new ones.

The critical detail in batch publishing is preserving dates. Most APIs accept a publishedAt field — set it to the original publication date, not the current time. This preserves your content's chronological order and prevents search engines from treating migrated content as newly published (which can trigger duplicate content issues if the old URLs still exist).

Webhook-driven publishing workflows

Webhooks reverse the API flow: instead of your script calling the platform, the platform calls your script when something happens. Common webhook triggers for publishing workflows:

  • Post published: Trigger social media sharing, email newsletter send, or cross-platform syndication
  • Post updated: Refresh CDN cache, update syndicated copies, notify subscribers of corrections
  • Image uploaded: Trigger image optimization, generate responsive sizes, update CDN
  • SEO score changed: Alert editors when a post's score drops below threshold (content drift)

Webhooks and API publishing work together: publish content through the API, then let webhooks handle everything that should happen after publication. This event-driven architecture scales better than monolithic scripts that try to do everything sequentially.

Authentication patterns compared

Authentication is the first hurdle in API publishing, and each platform handles it differently. The authentication method matters more than developers realize — it determines onboarding friction, security posture, and how easily non-developers can integrate.

Bearer token (Modern Blogging): The simplest pattern. Generate a key once, include it in every request as an Authorization header. No token exchange, no expiry, no refresh flow. Revoke and regenerate if compromised. This is the same pattern GitHub, Stripe, and OpenAI use — developers already know it.

JWT signing (Ghost): Ghost requires splitting an API key into ID and secret, hex-decoding the secret, signing a JWT with HS256, setting a 5-minute expiry, and including the audience claim. This is correct from a cryptographic perspective but adds 10-15 lines of boilerplate to every integration. For simple publish scripts, it is more ceremony than security benefit.

Application passwords (WordPress): WordPress uses HTTP Basic Auth with application passwords. Simple to use, but Basic Auth sends credentials in every request (base64-encoded, not encrypted). This is secure over HTTPS but feels dated. The WordPress approach also lacks per-key scoping — an application password has full access to the user's capabilities.

Personal access tokens (Hashnode): Similar to bearer tokens but generated per-user rather than per-blog. Good for individual developers, less ideal for team workflows where you want a service account key separate from any individual.

Error handling and retries

API publishing can fail for many reasons. Robust error handling is essential:

javascript
async function publishWithRetry(postData, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    const response = await fetch(API_URL, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' },
      body: JSON.stringify(postData),
    })

    if (response.ok) return await response.json()

    const error = await response.json()

    if (response.status === 409) {
      // Slug conflict — append suffix and retry
      postData.slug = `${postData.slug}-${attempt}`
      continue
    }

    if (response.status === 429) {
      // Rate limited — wait and retry
      const retryAfter = response.headers.get('Retry-After') || 60
      await new Promise(r => setTimeout(r, retryAfter * 1000))
      continue
    }

    if (response.status >= 500) {
      // Server error — exponential backoff
      await new Promise(r => setTimeout(r, Math.pow(2, attempt) * 1000))
      continue
    }

    throw new Error(`API error ${response.status}: ${JSON.stringify(error)}`)
  }
  throw new Error('Max retries exceeded')
}

Security best practices

  • Never commit API keys to Git. Use environment variables or secret managers (GitHub Secrets, Cloudflare Secrets).
  • Use read-only keys where possible. The Content API key should be separate from the Admin/Write API key.
  • Rotate keys regularly. If a key is exposed, revoke it immediately and generate a new one.
  • Validate input before sending. Sanitize content to prevent XSS in published posts.
  • Log API calls. Track what was published, when, and by which key — for auditing and debugging.
Security checklist for API-based blog publishing showing key management, input validation, rate limiting, and monitoring best practices
API publishing security best practices
Six-stage API publishing pipeline: content source, transformation, validation, publishing, verification, and notification
Complete API publishing pipeline

Testing API publishing before going live

Never publish directly to production the first time you use a platform's API. Every platform handles edge cases differently, and discovering them on your live blog is costly.

Create a test blog. On Modern Blogging, create a separate blog for API testing. Test post creation, image uploads, slug conflicts, special characters in titles, and long content. Verify that the published output matches your expectations. Delete the test posts when done.

Validate responses. After each API call, verify the response body contains the expected fields. Check that the slug was set correctly (some platforms modify slugs), the publication date is right, categories are assigned, and SEO metadata appears in the page source.

Test error cases. Send malformed JSON, exceed field length limits, reference nonexistent categories, upload oversized images, and use duplicate slugs. Verify your error handling catches each case. A robust publishing pipeline handles failures gracefully rather than crashing.

Measure performance. Time your API calls. Modern Blogging's API responds in under 200ms for post creation. If your pipeline publishes 100 posts in a migration, the total API time should be under 20 seconds. If it is significantly slower, check network latency, payload size, and whether you are being rate-limited.

Monitoring published content

Publishing via API removes the visual verification step of the web editor. After publishing, automated checks should verify that content rendered correctly.

Fetch the published URL and verify HTTP 200 status. Check that the page title matches what you sent. Verify meta description and Open Graph tags in the HTML source. Confirm images load by requesting each image URL. Run a Lighthouse audit on the published page to catch rendering issues.

Modern Blogging's edge rendering makes verification faster — content is available globally within seconds of the API response. Platforms with build steps (static site generators, some headless CMS setups) may take minutes to deploy, requiring a polling approach before verification.

Frequently asked questions

When should I use API publishing vs the web editor?

Use the web editor for one-off posts where you want visual preview and real-time SEO feedback. Use API publishing when you have a repeatable workflow: CI/CD pipelines, content migration, syndication to multiple platforms, AI-generated content, or any process that runs without manual intervention. Many publishers use both — draft in the editor, publish final versions through API-triggered pipelines.

Which API style is best: REST or GraphQL?

REST is simpler for CRUD operations (create, read, update, delete posts). GraphQL is better when you need flexible queries that fetch only specific fields. For blog publishing, REST is usually sufficient. Modern Blogging and Ghost use REST; Hashnode uses GraphQL.

How do I handle authentication securely in CI/CD?

Store API keys as encrypted secrets in your CI platform (GitHub Secrets, GitLab CI/CD variables, or environment-level secrets in your deployment provider). Never commit keys to repositories, even private ones — Git history is permanent. Use the CI platform's native secret injection so keys appear as environment variables at runtime but never in logs, artifacts, or configuration files. Rotate keys periodically and immediately if any CI logs are accidentally made public.

What happens if I publish a post with a duplicate slug?

Behavior varies by platform. Modern Blogging returns a 409 conflict error with a clear message. Ghost silently appends a number suffix (my-post becomes my-post-2). WordPress creates the post with a modified slug. The safe approach: check if a slug exists (GET the slug) before publishing, and handle the conflict in your code rather than relying on the platform's default behavior.

Can I schedule posts via API?

Most platforms support scheduling by setting a future publishedAt date. Modern Blogging, Ghost, and WordPress all support this. The post is created immediately but only becomes publicly visible at the scheduled time.

How do I handle Markdown to HTML conversion?

Use established libraries: marked, markdown-it, or remark for JavaScript; python-markdown for Python; goldmark for Go. Convert locally before sending to the API, since most platforms accept HTML. Modern Blogging also accepts Markdown directly.

What about images in API-published posts?

Upload images separately through the platform's image API, get the URL back, then reference that URL in your post content. Modern Blogging stores images on a global CDN backed by Cloudflare R2, delivering fast load times regardless of where your readers are. Ghost uses its own image storage. WordPress stores images in the wp-content/uploads directory. See the programmatic publishing guide for the complete image workflow including batch upload, responsive sizing, and alt text management.

Can I use the same API script for multiple blogs?

Yes. Parameterize your publishing script with the blog URL and API key as environment variables. The same Node.js or Python script works across any number of Modern Blogging instances. For Ghost, the JWT signing logic is the same regardless of the blog. For WordPress, the REST API endpoints are identical across installations. The only differences are the base URL and authentication credentials — keep those in configuration files or environment variables, and one script serves all your blogs.

What is the best language for API publishing scripts?

JavaScript or Python. Both have excellent HTTP libraries, run everywhere, and have large ecosystems for content transformation (Markdown parsing, HTML sanitization, image processing). JavaScript is natural if your content pipeline already uses Node.js tools. Python is better for data-heavy pipelines that involve scraping, transformation, or machine learning. For simple publish scripts, either works equally well — choose whichever you are most productive in.

Is MCP better than REST for publishing?

They serve different use cases. MCP is better for AI-driven workflows where an AI assistant manages the publishing process through natural conversation. REST is better for deterministic automation: scripts, CI pipelines, and batch operations where you want predictable, repeatable behavior.

MCP wraps REST operations in natural-language tool calls that AI assistants understand natively. The AI decides which API calls to make based on your instructions. Use MCP when an AI assistant is part of the publishing workflow. Use REST when a script or CI pipeline handles publishing without AI involvement. Modern Blogging supports both approaches with the same underlying capabilities. See the MCP tools guide for the full tool catalog and integration instructions.

Share this post
𝕏in
Built with Modern Blogging

This article was written, styled, and published using the Modern Blogging platform. Launch your own fast, SEO-ready publication in minutes.

Start for free →