2

I'm using WordPress rest API for developing my Android application. But I can not cache the response.

How can I add required headers to REST API response so that my app can save the response for offline reading?

5
  • what caching of any kind have to do with offline reading? if you need to store a response in your app, just store it. Aug 18, 2017 at 12:24
  • I'm using Volley which will automatically cache the response. But I it is not caching only WP rest API response. Do I need to add any headers to say volley to cache them? Aug 18, 2017 at 12:27
  • no idea what is volley ;) just doesn't sound right that caching info in an app depends on headers sent by the server. You can write a plugin to set headers on specific request, just sounds weird. Aug 18, 2017 at 12:31
  • Caching in the application depends on the headers of response we received. Read this: devcenter.heroku.com/articles/… I'm not a server guy and I don't know the exact terms to describe it. Aug 18, 2017 at 12:33
  • you can use this plugin wordpress.org/plugins/wp-rest-cache
    – user8889
    Aug 2, 2021 at 5:35

1 Answer 1

6

You should create a new instance from WP_REST_Response to set the Cache-Control value.

<?php
register_rest_route('wp/v2', '/your_endpoint', array(
    'methods' => 'GET',
    'callback' => 'function_callback',
));

function function_callback($data) {
  $response = array(
    1,2,3,4,5,6,7,8
  );

  $result = new WP_REST_Response($response, 200);

  // Set headers.
  $result->set_headers(array('Cache-Control' => 'max-age=3600'));

  return $result;
}

Click here to get more info about directives.

2
  • If the response is different depending on the $data that gets requested, will the $response that gets cached be specific to that $data, or would it just return the same cached response from previous requests? Nov 21, 2020 at 15:07
  • Will return the new response. Nov 22, 2020 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.