JSON rest API

POST, PUT, GET — это все HTTP-глаголы и сами по себе не указывают формат для передачи данных, поэтому нет формата POST. Это означает, что вы можете кодировать данные любым способом.

Теперь, в каком формате вы решите пойти, действительно должно быть больше зависит от того, как обычно будет использоваться ваш API. Если это будет в первую очередь подача формы из веб-браузера, то использование кодировки полей формы, скорее всего, наиболее разумно, поскольку это облегчает это взаимодействие для клиента.

С другой стороны, если вы в первую очередь собираетесь получать данные JSON из вызовов AJAX, то получение формата JSON может иметь смысл. Если вы сделаете обоим, нет никаких причин, по которым вы не можете принимать данные в обоих форматах.

Другим аспектом, который следует учитывать, является сложность структур данных, которые вы будете передавать назад и вперед. Кодирование формы (аналогично кодированию строки запроса) также является структурой ключевого значения, тогда как JSON (или XML) допускает гораздо более богатую структуру данных.

В конце концов, идите с тем, что проще всего для вас как на стороне сервера, так и на стороне клиента (поскольку я предполагаю, что вы также будете писать основного клиента-клиента рассматриваемого API). Простота всегда предпочтительна по сравнению со сложностью, пока вы не сможете окончательно показать, что большая сложность дает вам ощутимую выгоду.

Кроме того, последнее, о чем я расскажу, это то, что REST — это не просто чистые URL-адреса или правильные HTTP-глаголы. Эти аспекты на самом деле просто глазури на торте. Основная идея архитектуры REST заключается в том, что Hypertext — это механизм состояния приложения. Просто следуя URL-адресам в ответах сервера, хороший клиент может узнать обо всех доступных действиях и не должен знать ничего больше, чем базовый URL. Из этого можно обнаружить все остальное. Пара, которая имеет четко определенные типы контента, и у вас есть мир, где множество клиентов могут общаться с большим количеством серверов, все говорят на одном и том же «языке», и клиентам не нужно ничего знать о серверах (или наоборот) кроме базового URL-адреса и типов содержимого. Что такое REST.

qaru.site

JSON Example

Содержание

A sample JSON document looks like this:

//JSON Object  {   "employee": {   	"id": 		1,  "name": 	"Admin",   "location": 	"USA"  }  }  //JSON Array  {   "employees": [  			 {  			 	"id": 		1, 			 "name": 	"Admin",  			 "location": 	"USA" 			 }, 			 {  			 	"id": 		2, 			 "name": 	"User",  			 "location": 	"USA" 			 }, 			 {  			 	"id": 		3, 			 "name": 	"User2",  			 "location": 	"USA" 			 }  ]  } 

As you can see, JSON data consists of name/value pairs. These name/value pairs reflect the structure of the data.

Learn JSON

In this tutorial, we will learn various concepts about JSON with examples. Such as:

  • Difference with XML
  • Syntax and data types
  • How to read JSON data
  • How to write JSON data
  • Convert JSON to String and vice-versa etc.

Ref: Introducing JSON

restfulapi.net

Update: For more information, you can download our free ebook, The Ultimate Guide to the WordPress REST API

In my article on the future of WordPress, I wrote about how the introduction of a JSON RESTful API to WordPress core will radically expand WordPress’s reach and capabilities.

What is so exciting about this new REST API — which is currently available as a plugin, and slated to be included in WordPress 4.1 — is its ability to use it to not only display content from other WordPress sites, or even other applications entirely, but to save content from other sites, whether they are WordPress sites or not.

JSON REST API

In the past, this sort of integration was really only available through XML-RPC. However, the new REST API uses JSON, which is basically a universal connector for data on the internet. What used to be an incredibly complicated process with XML-RPC, can now be simplified by using the much more common JSON standard.

Most programming languages have an easy way to convert their standard data structures into JSON, and convert JSON into their standard data structures. For example, in PHP we have json_encode() and json_decode() to translate from PHP arrays or objects into JSON or the other way around. What this means on a practical level is that WordPress can be the data management tool for an application written in any language and it can easily send and receive data using the JSON standard.

So far the WordPress REST API has predominantly been used for powering single-page, client-side JavaScript apps, either as part of a WordPress theme or plugin, or in a separate front-end client that’s totally separated from the backend. There are some great resources already on how to do that.

I strongly recommend that you read Scott Bolinger’s tutorial on using the REST API to build a simple JavaScript mobile app, which is currently available on the AppPresser site.

The focus of this two-part tutorial will be on how to interact with the REST API using PHP. In this article, I’ll show you how to display posts retrieved via the API.

While the easiest way to test this is by showing posts from the same site, keep in mind that they could be coming from any site, and that the same process would apply to a JSON object sourced from another app or from another JSON API.

Next week, I’ll illustrate how to save and edit posts from a JSON array. Again, I’ll be using WordPress sites, but what makes this whole thing very cool is that the JSON object could be coming from any app or API. Ultimately the goal here is to illustrate just how easy it is to apply what you already know as a WordPress developer to integrate with this widely-used standard. This will enable you to work side-by-side with apps written in any language.

Before We Begin

Before we begin we’ll need to get set up on two sites. On both sites you will need to install the REST API plugin — as it’s not yet part of core.

To make life easier, I’ll be using just two of the default sites provided by VVV, running locally on my computer.

Since I’m using VVV, my two sites will be http://local.wordpress.dev and http://local.wordpress-trunk.dev/ . But you can use any two sites you want.

Since I’m working locally, I can use the basic authentication plugin. That will not be relevant until we talk about saving posts in next week’s article — so I’ll save that discussion for next time.

Just keep in mind that the basic authentication plugin shouldn’t be used on live servers, instead you should use oAuth plugin.

GETing and POSTing

The REST API works using four of the most common HTTP methods — GET, PUT, POST, and DELETE. We will be using GET and POST in this tutorial. We’ll use GET to obtain data via the API and display it, and we’ll use POST to update items. If you have not used a JSON REST API, it may sound complicated or intimidating, but really it’s a matter of creating the right URL strings and sending them in the browser.

In this section we’ll be using simple URL strings to get single posts or all posts. Later in this article I’ll show you how to filter which posts you query for, and how to get items in other post types including pages, attachments, and custom post types.

To illustrate a simple GET request, once you have the REST API installed, go in your browser to http://local.wordpress.dev/wp-json/posts/1 and you will see a JSON object for post ID #1, or a message telling you that you don’t have a post of that ID. If you remove the ID from the end of the URL you will see all posts.

Congrats you just made your first GET request to the JSON API!

Next week I’ll illustrate how to use POST actions to save posts.

(By the way, if GET and POST sound familiar from working with forms, that’s no coincidence, it’s the same thing. The amount of new things you are learning here is not very long.)

The WordPress HTTP API

The REST API isn’t the only impressive API that WordPress offers. One of the lesser used — compared to say the post API, hook API, or options API — is the HTTP API, which simplifies making HTTP requests. The HTTP request makes WORDS easy. With a few lines of code, we can use the HTTP API to turn a URL string into a JSON object.

The HTTP API gives us several useful functions to make HTTP requests via PHP. The simplest example would be:

If you were to output $json now, you would see that the return isn’t actually the JSON object we want. It’s an array, with an index called body, which has the JSON object. For the most part, that’s actually all we need. We can get the body directly with wp_remote_retrieve_body(). In general, we don’t want to use it directly though, as it will produce an error if the URL string passed isn’t valid.

So let’s put together the simplest PHP API client that will take a URL string and output a PHP array of post objects. Our mini-client is just one function. Take a look at it, I’ll explain it below:

This function starts from a URL string, and makes a GET request to load it into $request. Then we make sure that the request works by testing that $request is not an object of the WP_Error class, which is what it will be if the HTTP request failed. If so, we return an error message. If not, we pass $response to wp_remote_retrieve_body() to get the JSON object into $data. Again, we must check that we didn’t get an error, if we didn’t, we use json_decode() to return an array of post objects.

Go ahead and feed it a URL string like http://local.wordpress.dev/wp-json/posts/1 and run the results through print_r to see what you got. Where this gets really cool is if you pass it a URL string from another site. In my example set up in local.wordpress.dev, I can pass in the string http://local.wordpress-trunk.dev/wp-json/posts and see posts from the second site.

Making Queries

Just getting a specific post or all posts via the API is only so useful. What if we wanted specific posts based on various conditions, just like we’re use to doing with WP_Query. Luckily we have a subset of WP_Query parameters available to us with the REST API. Opposed to WP_Query, we can use it to query other sites.

By adding filter parameters to the URL string, we can query for post statuses other than the default ‘publish’ status, or we can change how many posts we return or how they ordered. We can even run a search by post title. For full documentation of these parameters, see the REST API documentation.

For example, if we wanted to retrieve 8 posts in reverse alphabetical order by post title, we could use this URL string:
http://local.wordpress.dev/wp-json/posts?filter[posts_per_page]=8&filter[order]=DESC

Typing out that URL is a pain, and I didn’t actually do it, since WordPress can do it for me. One way to do it is to use the function add_query_arg(). If we pass it an array of arguments as the first parameter, and use our base url as the second parameter, it will give us the right URL string.

For example, here is how I created it:

You can also choose to query for one or more post types using the posts[] parameter. For example, to query for a post in custom post types called “books” and “authors,” you would use this string:
http://local.wordpress.dev/wp-json/posts?type[]=book&type[]=author

Even with add_query_arg(), creating these strings can be complicated and tedious. Instead of continuing this way, let’s build a function to build these URL strings for us.

The function accepts a post type, or an array of post types, as well as an array of filters in the form of ‘filter_name’ => ‘value’. Here’s the function:

This function makes it really easy to build the type of URL strings we need for the REST API. For example, to get 50 posts in 4 different post types, ordered by their modified date, skipping the first 10 posts with this new function we can create the URL like this:

If you look closely, you will notice that the third parameter, $rooturl, can accept either a URL or a function name. This allows you to pass a function — such as the default, home_url(), or a full URL — to use as the base for building the URL string. The default value will query the current site’s API. Alternatively, we can pass in another site’s URL, or a function representing it to get posts from that site’s API. For example, to get pages from my other local development site I would enter:

Outputting the Posts with PHP

Getting these JSON objects is pretty awesome, but we need to be able to output the posts using the two functions I showed early. Together they give us an array of objects. Each object has a variety of property for all of the fields that make up a WordPress post.

Еще по теме:   Полностью автоматическая линия по производству респираторов для лица (N95)

This means that working with these objects is very much like working with the post objects that you’re probably used to working with when you access the global $post object, or when you get an object with get_post(). Here is a simple loop that iterates through all posts retrieved by the REST API, and outputs them in standard HTML5 markup, simplified from the content-single.php from _s:

I’m aware that what I’ve shown you above is an efficient way of doing what you can already do with a WordPress theme. I’m showing it to you for two very important reasons.

The first reason is because this exercise will familiarize you with the data that the REST API returns, and in turn shows just how easy it is to use. The second, and more important reason is that with almost exactly the same code, with a different URL, you can show posts from a completely different site, and that’s not something you can do already with WordPress.

torquemag.io

Why use the WordPress REST API #Why use the WordPress REST API

The WordPress REST API makes it easier than ever to use WordPress in new and exciting ways, such as creating Single Page Applications on top of WordPress. You could create a plugin to provide an entirely new admin experiences for WordPress, or create a brand new interactive front-end experience.

You would not even have to write the applications in PHP: any programming language that can make HTTP requests and interpret JSON can interact with WordPress through the REST API, from Node.js to Java and beyond.

The WordPress REST API can also serve as a strong replacement for the admin-ajax API in core. By using the REST API, you can more easily structure the way you want to get data into and out of WordPress. AJAX calls can be greatly simplified by using the REST API, enabling you to spend less time accessing the data you need and more time creating better user experiences.

Our imagination is the only limit to what can be done with the WordPress REST API. The bottom line is, if you want a structured, extensible, and simple way to get data in and out of WordPress over HTTP, you probably want to use the REST API. For all of its simplicity the REST API can feel quite complex at first, and we will attempt to break it down into smaller components so that we can easily piece together the full puzzle.

Top ↑

Key Concepts #Key Concepts

To get started with using the WordPress REST API we will break down some of the key concepts and terms associated with the API:

  • Routes/Endpoints
  • Requests
  • Responses
  • Schema
  • Controller Classes

Each of these concepts play a crucial role in using and understanding the WordPress REST API. Let’s briefly break them down so that we can later explore each in greater depth.

Routes & Endpoints #Routes & Endpoints

A route, in the context of the WordPress REST API, is a URI which can be mapped to different HTTP methods. The mapping of an individual HTTP method to a route is known as an “endpoint”. To clarify: If we make a GET request to http://oursite.com/wp-json/, we will get a JSON response showing us what routes are available, and within each route, what endpoints are available. /wp-json/ is a route itself and when a GET request is made it matches to the endpoint that displays what is known as the index for the WordPress REST API. We will learn how to register our own routes and endpoints in the following sections.

Top ↑

Requests #Requests

One of the primary classes in the WordPress REST API infrastructure is WP_REST_Request. This class is used to store and retrieve information for the current request; requests can be submitted remotely via HTTP but may also be made internally from PHP with WordPress. WP_REST_Request objects are automatically generated for you whenever you make an HTTP request to a registered route. The data specified in the request will determine what response you get back out of the API. There are a lot of neat things you can do using the request class. The request section will go into greater detail.

Top ↑

Responses #Responses

Responses are the data you get back from the API. The WP_REST_Response class provides a way to interact with the response data returned by endpoints. Responses can return the desired data, and they can also be used to return errors.

Top ↑

Schema #Schema

Each endpoint requires and provides slightly different data structures, and those structures are defined in the API Schema. The schema structures API data and provides a comprehensive list of all of the properties the API can return and input parameters it can accept. Schema also provides security benefits for the API, as it enables us to validate the requests being made to the API. The Schema section further explores this large topic.

Top ↑

Controller Classes #Controller Classes

As you can see, the WordPress REST API has a lot of moving parts that all need to work together. Controller classes bring all of these elements together in a single place. With a controller class you can manage the registration of routes & endpoints, handle requests, utilize schema, and generate API responses.

Top ↑

Next Steps #Next Steps

Let’s look at the reference for the WordPress REST API.

Поделиться:
Нет комментариев

Добавить комментарий

Ваш e-mail не будет опубликован. Все поля обязательны для заполнения.

×
Рекомендуем посмотреть
Adblock
detector