Publicado en C# - Csharp, MySQL, PHP, Visual Studio

C# Obtener datos desde una REST API en PHP

Para esta ocasión, veremos como ejecutar una API hecha en PHP y desplegar los datos devueltos en nuestra aplicación Windows Form.

Primero que nada, hay que construir la API en PHP con las consultas básicas. Yo tome de ejemplo este blog para crear una REST API en PHP.

Hecho la API, veremos su codigo para este ejemplo:

Este es el método que ejecutaremos:

if (!function_exists('get_employee'))
	{
		function get_employee($id=0)
		{
			global $connection;
			$query="SELECT * FROM employee";

			if($id != 0)
			{
				$query.=" WHERE id=".$id." LIMIT 1";
			}

			$response=array();
			
			$result=mysqli_query($connection, $query);
			while($row=mysqli_fetch_array($result))
			{
				$response[]=$row;
		
			}
			header('Content-Type: application/json');
			echo json_encode($response);
			}
	}

Los datos en la base MySql son estos:

Llamamos la API en el navegador

http://localhost:8080/api/v1/employees/65

Y nos devuelve este arreglo:

[{“0″:”65″,”id”:”65″,”1″:”nombre 2″,”employee_name”:”nombre 2″,”2″:”200000″,”employee_salary”:”200000″,”3″:”40″,”employee_age”:”40″}]

Ahora bien, veremos la forma de traer los datos desde la API nuestra aplicación.

Primero debemos instalar el Nuget Newtonsoft.Json

En este ejemplo, haremos dos llamadas: una que genere una entidad y otra con IEnumerable.

Primero creamos una clase con los atributos de la tabla de Empleados:

public class Empleado
        {
            [JsonProperty("id")]
            public int id { get; set; }
            [JsonProperty("employee_name")]
            public string employee_name { get; set; }
            [JsonProperty("employee_salary")]
            public string employee_salary { get; set; }
            [JsonProperty("employee_age")]
            public string employee_age { get; set; }
        }

Luego agregaremos el metodo que ejecutara la URL de la API

public string GetApiData(string url)
        {

            using (var httpClient = new HttpClient())
            {
                string contentType = "application/json";
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
                var userAgent = "d-fens HttpClient";
                httpClient.DefaultRequestHeaders.Add("User-Agent", userAgent);

                var response = httpClient.GetStringAsync(new Uri(url)).Result;

                return response;
            }
        }

Ahora veremos el codigo para obtener la entidad con datos desde la API:

        private void button1_Click(object sender, EventArgs e)
        {
            var output = GetApiData("http://localhost:8080/api/v1/employees/" + txtNroEmpleado.Text);
            
            Empleado myobj = JsonConvert.DeserializeObject<Empleado>(output.Substring(1, output.Length - 2));

            if (myobj != null)
            {
                txtEdad.Text = myobj.employee_age;
                txtNombre.Text = myobj.employee_name;
                txtSalario.Text = myobj.employee_salary;
            }
            else
            {
                MessageBox.Show("Sin datos");
            }
        }

Ponemos el numero del Empleados y obtenemos los datos:

Si ponemos otro código que no existe, muestra el mensaje de error:

Para obtener un IEnumerable desde la API es de esta forma y la ejecución es la misma que la anterior:

private void button2_Click(object sender, EventArgs e)
        {
            var output = GetApiData("http://localhost:8080/api/v1/employees/" + txtNroEmpleado.Text);

            IEnumerable<Empleado> result = JsonConvert.DeserializeObject<IEnumerable<Empleado>>(output);

            if (result.Count() > 0)
            {
                txtEdad.Text = result.First().employee_age;
                txtNombre.Text = result.First().employee_name;
                txtSalario.Text = result.First().employee_salary;
            }
            else
            {
                MessageBox.Show("Sin datos");
            }
        }

RESUMEN DEL CÓDIGO

Código Completo pagina connection.php

<?php
Class dbObj{
	/* Database connection start */
	var $servername = "localhost";
	var $username = "root";
	var $password = "xxxxxx";
	var $dbname = "test";
	var $conn;
	
	function getConnstring() {
		$con = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());

		/* check connection */
		if (mysqli_connect_errno()) {
			printf("Connect failed: %s\n", mysqli_connect_error());
			exit();
		} else {
			$this->conn = $con;
		}
		return $this->conn;
	}
}

?>

Código Completo pagina employees.php

<?php
	// Connect to database
	include("../connection.php");
	$db = new dbObj();
	$connection =  $db->getConnstring();
 
	$request_method=$_SERVER["REQUEST_METHOD"];
	
	if (!function_exists('get_employees'))
	{
		function get_employees()
		{
			global $connection;
			$query="SELECT * FROM employee";
			//echo $query;
			$response=array();
			$result=mysqli_query($connection, $query);
			while($row=mysqli_fetch_array($result))
			{
				$response[]=$row;
			}
			header('Content-Type: application/json');
			echo json_encode($response);
		}
	}
	
	if (!function_exists('get_employee'))
	{
		function get_employee($id=0)
		{
			global $connection;
			$query="SELECT * FROM employee";

			if($id != 0)
			{
				$query.=" WHERE id=".$id." LIMIT 1";
			}

			$response=array();
			
			$result=mysqli_query($connection, $query);
			while($row=mysqli_fetch_array($result))
			{
				$response[]=$row;
		
			}
			header('Content-Type: application/json');
			echo json_encode($response);
			}
	}
	function insert_employee()
	{
		global $connection;

		$data = json_decode(file_get_contents('php://input'), true);
		$employee_name=$data["employee_name"];
		$employee_salary=$data["employee_salary"];
		$employee_age=$data["employee_age"];
		echo $query="INSERT INTO employee SET employee_name='".$employee_name."', employee_salary='".$employee_salary."', employee_age='".$employee_age."'";
		if(mysqli_query($connection, $query))
		{
			$response=array(
				'status' => 1,
				'status_message' =>'Employee Added Successfully.'
			);
		}
		else
		{
			$response=array(
				'status' => 0,
				'status_message' =>'Employee Addition Failed.'
			);
		}
		header('Content-Type: application/json');
		echo json_encode($response);
	}
	
	function update_employee($id)
	{
		global $connection;
		$post_vars = json_decode(file_get_contents("php://input"),true);
		$employee_name=$post_vars["employee_name"];
		$employee_salary=$post_vars["employee_salary"];
		$employee_age=$post_vars["employee_age"];
		$query="UPDATE employee SET employee_name='".$employee_name."', employee_salary='".$employee_salary."', employee_age='".$employee_age."' WHERE id=".$id;
		if(mysqli_query($connection, $query))
		{
			$response=array(
				'status' => 1,
				'status_message' =>'Employee Updated Successfully.'
			);
		}
		else
		{
			$response=array(
				'status' => 0,
				'status_message' =>'Employee Updation Failed.'
			);
		}
		header('Content-Type: application/json');
		echo json_encode($response);
	}
	
	function delete_employee($id)
	{
		global $connection;
		$query="DELETE FROM employee WHERE id=".$id;
		if(mysqli_query($connection, $query))
		{
			$response=array(
				'status' => 1,
				'status_message' =>'Employee Deleted Successfully.'
			);
		}
		else
		{
			$response=array(
				'status' => 0,
				'status_message' =>'Employee Deletion Failed.'
			);
		}
		header('Content-Type: application/json');
		echo json_encode($response);
	}
	
	/***/
	function CallAPI($method, $api, $data) 
	{
		$url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

		switch ($method) {
			case "GET":
				curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
				curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
				break;
			case "POST":
				curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
				curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
				break;
			case "PUT":
				curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
				curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
				break;
			case "DELETE":
				curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
				curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
				break;
		}
		$response = curl_exec($curl);
		$data = json_decode($response);

		/* Check for 404 (file not found). */
		$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		// Check the HTTP Status code
		switch ($httpCode) {
			case 200:
				$error_status = "200: Success";
				return ($data);
				break;
			case 404:
				$error_status = "404: API Not found";
				break;
			case 500:
				$error_status = "500: servers replied with an error.";
				break;
			case 502:
				$error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
				break;
			case 503:
				$error_status = "503: service unavailable. Hopefully they'll be OK soon!";
				break;
			default:
				$error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
				break;
		}
		curl_close($curl);
		echo $error_status;
		die;
	}
	
	/*
	
	//CALL Delete Method
	$data = array('id'=>$_GET['did']);
	$result = CallAPI('DELETE', "DeleteCategory", $data);
	
	//CALL Post Method
	$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
	$result = CallAPI('POST', "InsertCategory", $data);
	
	//CALL Get Method
	$data = array('id'=>$_GET['eid']);
	$result = CallAPI('GET', "GetCategoryById", $data);
	
	//CALL Put Method
	$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
	$result = CallAPI('POST', "UpdateCategory", $data);
	*/
	
	/***/

	switch($request_method)
	{
		case 'GET':
			// Retrive Products
			
			if(!empty($_GET["id"]))
			{
				//echo "GET id=".$_GET["id"]."<br>";
				$id=intval($_GET["id"]);
				get_employee($id);
			}
			else
			{
				//echo "GET all";
				get_employees();
			}
			break;
		case 'POST':
			// Insert Product
			insert_employee();
			break;
		case 'PUT':
			// Update Product
			$id=intval($_GET["id"]);
			update_employee($id);
			break;
		case 'DELETE':
			// Delete Product
			$id=intval($_GET["id"]);
			delete_employee($id);
			break;
		default:
			// Invalid Request Method
			header("HTTP/1.0 405 Method Not Allowed");
			break;
	}

	
	
?>

Código .htaccess

RewriteEngine On # Turn on the rewriting engine
RewriteRule ^employees/?$ employees.php [NC,L]
RewriteRule ^employees/([0-9]+)/?$ employees.php?id=$1 [NC,L]

Código completo del formulario windows


using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace PHPApi
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public class Empleado
        {
            [JsonProperty("id")]
            public int id { get; set; }
            [JsonProperty("employee_name")]
            public string employee_name { get; set; }
            [JsonProperty("employee_salary")]
            public string employee_salary { get; set; }
            [JsonProperty("employee_age")]
            public string employee_age { get; set; }
        }

        public string GetApiData(string url)
        {

            using (var httpClient = new HttpClient())
            {
                string contentType = "application/json";
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
                var userAgent = "d-fens HttpClient";
                httpClient.DefaultRequestHeaders.Add("User-Agent", userAgent);

                var response = httpClient.GetStringAsync(new Uri(url)).Result;

                return response;
            }
        }

        private Empleado LoadFromJson(string response)
        {
            //var emp = LoadFromJson(output.Substring(1, output.Length - 2));
            JsonSerializerSettings serSettings = new JsonSerializerSettings();
            serSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            Empleado outObject = JsonConvert.DeserializeObject<Empleado>(response, serSettings);

            return outObject;
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            var output = GetApiData("http://localhost:8080/api/v1/employees/" + txtNroEmpleado.Text);
            
            Empleado myobj = JsonConvert.DeserializeObject<Empleado>(output.Substring(1, output.Length - 2));

            if (myobj != null)
            {
                txtEdad.Text = myobj.employee_age;
                txtNombre.Text = myobj.employee_name;
                txtSalario.Text = myobj.employee_salary;
            }
            else
            {
                MessageBox.Show("Sin datos");
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var output = GetApiData("http://localhost:8080/api/v1/employees/" + txtNroEmpleado.Text);

            IEnumerable<Empleado> result = JsonConvert.DeserializeObject<IEnumerable<Empleado>>(output);

            if (result.Count() > 0)
            {
                txtEdad.Text = result.First().employee_age;
                txtNombre.Text = result.First().employee_name;
                txtSalario.Text = result.First().employee_salary;
            }
            else
            {
                MessageBox.Show("Sin datos");
            }
        }

        
    }
}

Damos las gracias a http://www.stackoverflow.com por hacer posible este tutorial 😉

TYDW.-

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s