How to make a Json webservice from presenter

2 years ago

IdenticalWorlds
Member | 12
+
0
-

Hi,

I found Json in Utils, but I haven't found documentation on how to call the service. I followed the documentation on this page: https://doc.nette.org/en/2.4/json and added a method in a presenter.

But now my question is, how do I call it so I get the response?

Thanks in advance!

2 years ago

Pavel Kravčík
Member | 979
+
0
-
//presenter
$this->sendResponse(new JsonResponse(['array' => 1]));

2 years ago

IdenticalWorlds
Member | 12
+
0
-

Thanks for your quick reply.

Do I need to send it to its own latte and do I need to set a content type for this latte? How would I call the response there?

2 years ago

nightfish
Member | 143
+
0
-

IdenticalWorlds wrote:

Thanks for your quick reply.

Do I need to send it to its own latte and do I need to set a content type for this latte? How would I call the response there?

When you send JSON with sendResponse (usually in an actionSomething or renderSomething method), the presenter immediately terminates, so no corresponding latte is rendered. Also the sendResponse method sets the correct Content-Type header.

I'm not sure what you mean by calling the response, could you please clarify? Do you want to call it from your application or from the outside? You just have to access the action's URL (e.g. via curl or file_get_contents()).

Last edited by nightfish (2017-07-12 10:49)

2 years ago

IdenticalWorlds
Member | 12
+
0
-

Ah, great – I saw in other frameworks that you have to set the content-type header and wondered whether this would be the same in Nette. Good to know that it already does that. Calling the response in a corresponding latte is not necessary, so you can ignore that question.

I want to call it from the outside and I'm wondering how I can test if it works. What would the action URL be? Like you mentioned file_get_contents for example, what would it be in that function?

2 years ago

nightfish
Member | 143
+
0
-

IdenticalWorlds wrote:

I want to call it from the outside and I'm wondering how I can test if it works. What would the action URL be? Like you mentioned file_get_contents for example, what would it be in that function?

You would use the same URL as if it were a standard presenter with latte template. (The specific URL depends on the setup of your Router and whether you use pretty URLs. See routing docs for more info about this.

2 years ago

CZechBoY
Member | 3363
+
+3
-

btw you can use shortcut

$presenter->sendJson($data); // $data is something implementing JsonSerializable