<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>REST archivos - KumbiaPHP Framework PHP en español</title>
	<atom:link href="https://kumbiaphp.com/blog/category/rest/feed/" rel="self" type="application/rss+xml" />
	<link>https://kumbiaphp.com/blog/category/rest/</link>
	<description>Web &#38; app MVC PHP framework</description>
	<lastBuildDate>Fri, 22 Dec 2017 11:23:04 +0000</lastBuildDate>
	<language>es</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://kumbiaphp.com/blog/wp-content/uploads/2016/01/250-150x150.png</url>
	<title>REST archivos - KumbiaPHP Framework PHP en español</title>
	<link>https://kumbiaphp.com/blog/category/rest/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">123854898</site>	<item>
		<title>How to create a REST Service with Basic Auth in KumbiaPHP</title>
		<link>https://kumbiaphp.com/blog/2015/10/26/how-to-create-a-rest-service-with-basic-auth-in-kumbiaphp/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-create-a-rest-service-with-basic-auth-in-kumbiaphp</link>
					<comments>https://kumbiaphp.com/blog/2015/10/26/how-to-create-a-rest-service-with-basic-auth-in-kumbiaphp/#respond</comments>
		
		<dc:creator><![CDATA[Alberto Berroteran]]></dc:creator>
		<pubDate>Mon, 26 Oct 2015 02:04:16 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[API]]></category>
		<guid isPermaLink="false">http://www.kumbiaphp.com/blog/?p=900</guid>

					<description><![CDATA[<p>In the last post, we explained how to create a basic REST service. But everybody can access to it.&#8230;</p>
<p>La entrada <a href="https://kumbiaphp.com/blog/2015/10/26/how-to-create-a-rest-service-with-basic-auth-in-kumbiaphp/">How to create a REST Service with Basic Auth in KumbiaPHP</a> se publicó primero en <a href="https://kumbiaphp.com/blog">KumbiaPHP Framework PHP en español</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the last <a href="https://www.kumbiaphp.com/blog/2015/02/03/servicios-rest-con-kumbiaphp/" target="_blank" rel="noopener">post</a>, we explained how to create a basic REST service. But everybody can access to it. What do if we want to make it  accessible only for authenticated users? There are a few authentication methods for REST service, and the most used of them is the <a href="https://en.wikipedia.org/wiki/OAuth" target="_blank" rel="noopener">OAuth, </a>but today we shall speak about another  method more simple called <a href="https://en.wikipedia.org/wiki/Basic_access_authentication" target="_blank" rel="noopener">Basic Auth</a>.</p>
<p><span id="more-900"></span></p>
<p>We shall skip the database connection and we shall use a static array for the data. This is the PHP code:</p>
<p>File: <em>app/controllers/framework_controller.php</em></p>
<pre><code class="language-php">
&lt;?php

class FrameworkController extends RestController {

    protected $fw = array(1 =&gt; array(
            &quot;name&quot; =&gt; &quot;KumbiaPHP&quot;,
            &quot;description&quot; =&gt; &quot;The best PHP framework on the world&quot;
        ),
        array(
            &quot;name&quot; =&gt; &quot;Laravel&quot;,
            &quot;description&quot; =&gt; &quot;The new boy in the neighbourhood&quot;
        ),
        array(
            &quot;name&quot; =&gt; &quot;Symfony&quot;,
            &quot;description&quot; =&gt; &quot;The old veteran man&quot;
        ),
    );

    public function get($id) {
        if (isset($this-&gt;fw[$id])) {
            $this-&gt;data = $this-&gt;fw[$id];
        } else {
            $this-&gt;error(&#039;This framework doesn\&#039;t exist&#039;, 404);
        }
    }

    public function getAll() {
        $this-&gt;data = $this-&gt;fw;
    }

}
</code></pre>
<p>We created a new controller called Framework controller with two actions: <em>getAll</em> for getting all frameworks, and <em>get</em> for getting a framework by id. But this controller is still accessible for all users.  Now, we shall open the <em>rest_controller.php</em> file <span id="result_box" class="short_text" lang="en"><span class="hps">located in the directory</span></span><em> default\app\libs. </em>Add the user&#8217;s data for the authentication in an array and add the  validation in the initialize method.</p>
<pre><code class="language-php">
&lt;?php

require_once CORE_PATH . &#039;kumbia/kumbia_rest.php&#039;;

class RestController extends KumbiaRest {

    protected $users = array(
        &#039;alberto&#039; =&gt; &#039;123456&#039;,
        &#039;ashrey&#039; =&gt; &#039;0000&#039;
    );

    final protected function initialize() {
        $user = isset($_SERVER[&#039;PHP_AUTH_USER&#039;]) ? filter_var($_SERVER[&#039;PHP_AUTH_USER&#039;]) : null;
        $pass = isset($_SERVER[&#039;PHP_AUTH_PW&#039;]) ? filter_var($_SERVER[&#039;PHP_AUTH_PW&#039;]) : null;
        if (isset($this-&gt;users[$user]) &amp;&amp; ($this-&gt;users[$user] == $pass)) {
            return true;
        } else {
            $this-&gt;data = $this-&gt;error(&quot;Fail authentication&quot;, 401);
            header(&#039;WWW-Authenticate: Basic realm=&quot;Private Area&quot;&#039;);
            return false;
        }
    }

    final protected function finalize() {
        
    }

}
</code></pre>
<p>Now, you need to send a valid user and password for access to the results. You can use a tool like Postman or HttpRequester for to test, or your browser. Using Firefox, you will look a dialogue like:</p>
<p><a href="https://www.kumbiaphp.com/blog/wp-content/uploads/2015/10/2.png"><img decoding="async" class="size-medium wp-image-903" src="https://www.kumbiaphp.com/blog/wp-content/uploads/2015/10/2-300x103.png" alt="auth dialog" width="300" height="103" srcset="https://kumbiaphp.com/blog/wp-content/uploads/2015/10/2-300x103.png 300w, https://kumbiaphp.com/blog/wp-content/uploads/2015/10/2.png 589w" sizes="(max-width: 300px) 100vw, 300px" /></a><br />
 If you type a correct user and password you can see a page like:</p>
<p><a href="https://www.kumbiaphp.com/blog/wp-content/uploads/2015/10/3.png"><img fetchpriority="high" decoding="async" class="alignnone size-medium wp-image-904" src="https://www.kumbiaphp.com/blog/wp-content/uploads/2015/10/3-300x189.png" alt="Frameworks list" width="300" height="189" srcset="https://kumbiaphp.com/blog/wp-content/uploads/2015/10/3-300x189.png 300w, https://kumbiaphp.com/blog/wp-content/uploads/2015/10/3.png 480w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>else you will see a page like:</p>
<p><a href="https://www.kumbiaphp.com/blog/wp-content/uploads/2015/10/1.png"><img decoding="async" class="alignnone size-full wp-image-906" src="https://www.kumbiaphp.com/blog/wp-content/uploads/2015/10/1.png" alt="Fail authentication" width="277" height="95" /></a></p>
<p>La entrada <a href="https://kumbiaphp.com/blog/2015/10/26/how-to-create-a-rest-service-with-basic-auth-in-kumbiaphp/">How to create a REST Service with Basic Auth in KumbiaPHP</a> se publicó primero en <a href="https://kumbiaphp.com/blog">KumbiaPHP Framework PHP en español</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://kumbiaphp.com/blog/2015/10/26/how-to-create-a-rest-service-with-basic-auth-in-kumbiaphp/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">900</post-id>	</item>
		<item>
		<title>Servicios REST con KumbiaPHP</title>
		<link>https://kumbiaphp.com/blog/2015/02/03/servicios-rest-con-kumbiaphp/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=servicios-rest-con-kumbiaphp</link>
					<comments>https://kumbiaphp.com/blog/2015/02/03/servicios-rest-con-kumbiaphp/#comments</comments>
		
		<dc:creator><![CDATA[Govani]]></dc:creator>
		<pubDate>Mon, 02 Feb 2015 23:47:43 +0000</pubDate>
				<category><![CDATA[REST]]></category>
		<category><![CDATA[Tutoriales y screencast]]></category>
		<category><![CDATA[ejemplos]]></category>
		<guid isPermaLink="false">http://www.kumbiaphp.com/blog/?p=872</guid>

					<description><![CDATA[<p>KumbiaPHP incorpora un controlador llamado RestController el cual nos viene de gran  ayuda al momento de crear servicios REST&#8230;</p>
<p>La entrada <a href="https://kumbiaphp.com/blog/2015/02/03/servicios-rest-con-kumbiaphp/">Servicios REST con KumbiaPHP</a> se publicó primero en <a href="https://kumbiaphp.com/blog">KumbiaPHP Framework PHP en español</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>KumbiaPHP incorpora un controlador llamado RestController el cual nos viene de gran  ayuda al momento de crear servicios REST ya que nosotros solo nos preocupamos por los datos a devolver  y manipular los recibidos y este controlador le dará formato en json, xml o csv según corresponda o nosotros especifiquemos.</p>
<p>Ahora veremos cómo empezar!!<span id="more-872"></span></p>
<p>Crearemos un controlador como siempre lo hemos realizado con la diferencia que ahora lo vamos a extender de RestController</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2320" src="http://soyprogramador.liz.mx/wp-content/uploads/2015/02/kumbia-rest-II.jpg" alt="kumbia rest II" width="486" height="102" /></p>
<p>En el código anterior he creado un controlador llamado services, el cual al momento de recibir una petición GET invocara a la acción get, Por default cada acción se llama como el método usado por el cliente  como pueden ser  GET, POST, PUT, DELETE, OPTIONS, y demás.</p>
<p>Por lo cual en un controlador REST podríamos tener al menos 4 acciones</p>
<blockquote>
<p>Public function get($id){}</p>
<p>Public function post($id){}</p>
<p>Public function put($id){}</p>
<p>Public function delete($id){}</p>
</blockquote>
<p>Pero muchas veces necesitamos algo más que eso, para ello podemos hacer uso de la convención de nombre para servicios rest de KumbiaPHP el cual es:</p>
<p>get_nombre_accion()</p>
<p>post_nombre_acccion()</p>
<p>Por ejemplo en la clase servicio tendré un método para buscar un artículo, mi método se llama buscarArt y cómo va atender las peticiones get pasara a llamarse get_buscarArt($id) quedando de la siguiente manera:<img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2319" src="http://soyprogramador.liz.mx/wp-content/uploads/2015/02/kumbia-rest-III.jpg" alt="kumbia rest III" width="491" height="108" /></p>
<p>Como se puede observar el formato de salida es Json, en la siguiente imagen vemos los datos devuelto por la aplicación.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2312" src="http://soyprogramador.liz.mx/wp-content/uploads/2015/02/Boutique-Mozilla-Firefox_2.jpg" alt="Boutique - Mozilla Firefox_2" width="515" height="254" /></p>
<p>POST</p>
<p>Ahora mi aplicación en el lado del cliente enviara al servidor la información para guardar la nota venta, dicha petición será mediante post.</p>
<p>En este caso como no especifico la acción a guardar KumbiaPHP por default  buscara y ejecutara la acción post.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2313" src="http://soyprogramador.liz.mx/wp-content/uploads/2015/02/kumbiaphp-post-rest.jpg" alt="kumbiaphp post rest" width="635" height="235" /></p>
<p>Ahora para recibir la información que estoy enviando desde el cliente, simplemente invocamos al método $this-&gt;param(); el cual contendrá los datos enviados.</p>
<p>Como observamos empiezo por recorrer los artículos enviados en el <em>carrito</em> y posteriormente los datos de la venta.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2314" src="http://soyprogramador.liz.mx/wp-content/uploads/2015/02/kumbiaphp-post-rest-accion.jpg" alt="kumbiaphp post rest accion" width="479" height="268" /></p>
<p>Al final le regresare prácticamente la misma información al cliente, pero si observamos ahora el id tiene ya un valor, lo que el cliente interpretara que la inserción fue correcta.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2315" src="http://soyprogramador.liz.mx/wp-content/uploads/2015/02/kumbiaphp-post-response.jpg" alt="kumbiaphp post response" width="638" height="191" /></p>
<p>Para regresar lo anterior de la imagen: en cada iteración del carrito y conforme guardaba un artículo en base de datos, también lo almacenaba en un array, para los primeros tres datos solo se sobrescribían (esto se puede optimizar)</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2316" src="http://soyprogramador.liz.mx/wp-content/uploads/2015/02/kumbiaphp-data-response.jpg" alt="kumbiaphp data response" width="499" height="208" /></p>
<p>La entrada <a href="https://kumbiaphp.com/blog/2015/02/03/servicios-rest-con-kumbiaphp/">Servicios REST con KumbiaPHP</a> se publicó primero en <a href="https://kumbiaphp.com/blog">KumbiaPHP Framework PHP en español</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://kumbiaphp.com/blog/2015/02/03/servicios-rest-con-kumbiaphp/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">872</post-id>	</item>
	</channel>
</rss>
