How to get WordPress API key for JSON API

Introduction

Integrating the WordPress REST API into your application or website can enhance its capabilities by allowing you to access, manipulate, and display WordPress content. Understanding how to get a WordPress API key is essential for making secure wp-json API calls. In this tutorial, we’ll guide you through the process step-by-step.

Prerequisites

Before starting, ensure you have the following:

  • An active WordPress site.
  • Administrative access to your WordPress dashboard.
  • Basic knowledge of making HTTP requests.

Steps to Get API Key

WordPress REST API does not require a specific API key for read-only requests. However, for write operations, you’ll need to enable authentication. Below we outline how to create an API key using a plugin for authentication.

  1. Log in to your WordPress admin dashboard.
  2. Navigate to ‘Plugins’ and click on ‘Add New’.
  3. Search for the ‘Application Passwords’ plugin or any similar plugin that allows API key generation for users.
  4. Install and activate the plugin.
  5. Go to ‘Users’, then select your profile or the user you wish to generate an API key for.
  6. Scroll down to the ‘Application Passwords’ section.
  7. Enter a name for the new application password and click ‘Add New’.
  8. The new API key is displayed. Copy and store the key in a secure place as it will not be shown again.

Making API Calls

With the API key, you can now make authenticated requests to your WordPress site’s REST API. Below is an example using cURL in the command line:

  curl -X POST -u username:api_key http://yourdomain.com/wp-json/wp/v2/posts/ -d "title=Example Post&content=This is an example post&status=publish"

Output:

  {
    "id": 123,
    "date": "2023-04-06T12:00:00",
    "slug": "example-post",
    "status": "publish",
    ...
  }

Troubleshooting Tips

  • If you encounter a “401 Unauthorized” error, double-check your API key and username.
  • For “404 Not Found” errors, verify the endpoint URL and ensure your website’s permalinks are set to ‘Post name’ in Settings > Permalinks.
  • Remember to replace ‘username’ and ‘api_key’ with your actual WordPress username and API key in the cURL request.

Additional Resources

Conclusive Summary

Getting a WordPress API key is straightforward, especially with plugins like ‘Application Passwords.’ This key opens up numerous possibilities for managing your WordPress content programmatically. Remember to keep your API key secure and use it wisely. By following the steps in this tutorial, you’re now equipped to extend the functionality of your WordPress site with the REST API.