etru_RU

Veebirakenduste loomine API päringute abil

Uue projekti loomine

Paneme nimeks “veeb_TARpv23”.

ggg

Esmaste API päringute tegemine

Loome kausta Controllers

Valime API Controller – Empty ja nimetame faili PrimitiividController.cs

PrimitiividController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace veeb_TARpv23.Controllers
{
    [Route("api/[controller]")] 
    [ApiController] 
    public class PrimitiividController : ControllerBase
    {
        [HttpGet("hello-world")]
        public string HelloWorld()
        {
            return "Hello world at " + DateTime.Now;
        }

        [HttpGet("hello-variable/{nimi}")]
        public string HelloVariable(string nimi)
        {
            return "Hello " + nimi;
        }

        [HttpGet("add/{nr1}/{nr2}")]
        public int AddNumbers(int nr1, int nr2)
        {
            return nr1 + nr2;
        }

        [HttpGet("multiply/{nr1}/{nr2}")]
        public int Multiply(int nr1, int nr2)
        {
            return nr1 * nr2;
        }

        [HttpGet("do-logs/{arv}")]
        public void DoLogs(int arv)
        {
            for (int i = 0; i < arv; i++)
            {
                Console.WriteLine("See on logi nr " + i);
            }
        }
    }
}

Kausta Models ja Toode.cs

namespace veeb_TARpv23.Models
{
    public class Toode
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public bool IsActive { get; set; }

        public Toode(int id, string name, double price, bool isActive)
        {
            Id = id;
            Name = name;
            Price = price;
            IsActive = isActive;
        }
    }
}

ToodeController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using veeb_TARpv23.Models;

namespace veeb_TARpv23.Controllers
{
    [Route("api/[controller]")] 
    [ApiController] 
    public class ToodeController : ControllerBase
    {
        private static Toode _toode = new Toode(1, "Koola", 1.5, true);

        [HttpGet]
        public Toode GetToode()
        {
            return _toode;
        }

        [HttpGet("suurenda-hinda")]
        public Toode SuurendaHinda()
        {
            _toode.Price = _toode.Price + 1;
            return _toode;
        }

    }
}

TootedController.cs

Ise väljatöötatud meetodid

PrimitiividController.cs

[HttpGet("random-number/{nr1}/{nr2}")]
public int RandomNumber(int nr1, int nr2)
{
    if (nr1 > nr2)
    {
        int temp = nr1;
        nr1 = nr2;
        nr2 = temp;
    }
    Random random = new Random();
    return random.Next(nr1, nr2);
}


[HttpGet("age/{birthdayYears}")]
public string GetAge(int birthdayYears)
{
    DateTime currentdate = DateTime.Now;
    int age = currentdate.Year - birthdayYears;
    DateTime birthdayThisYear = new DateTime(currentdate.Year, 1, 1);
    if (currentdate < birthdayThisYear)
    {
        age--;
    }
    return $"Oled {age} aastat vana";
}

Toode.cs

[HttpGet("aktiivsust")]
public Toode Aktiivsus()
{
    _toode.IsActive = !_toode.IsActive;
    return _toode;
}

[HttpGet("nime-muutmine/{uusNimi}")]
public Toode NimeMuutmine(string uusNimi)
{
    _toode.Name = uusNimi;
    return _toode;
}

[HttpGet("muuda-hinda/{jarjekorranumber}")]
public Toode MuudaHind(int jarjekorranumber)
{
    if (jarjekorranumber <= 0)
    {
        throw new ArgumentException("Järjekorra number peab ületama nulli");
    }
    _toode.Price *= jarjekorranumber;
    return _toode;
}

Tooted.cs

[HttpGet("kustuta-koik")]
public string KustutaKoik()
{
    _tooted.Clear();
    return "Kõik tooted on kustutatud";
}

[HttpGet("aktiivsuse-muutuma")]
public List<Toode> MuutusAktiivne()
{
    foreach (var t in _tooted)
    {
        t.IsActive = false;
    }
    return _tooted;
}

[HttpGet("uks/{index}")]
public ActionResult<Toode> GetByIndex(int index)
{
    if (index < 0 || index >= _tooted.Count)
    {
        return NotFound("Toodet ei ole sellise indeksiga  ");
    }
    return _tooted[index];
}

[HttpGet("korge-hind")]
public ActionResult<Toode> GetKoigesuurem()
{
    if (_tooted.Count == 0)
    {
        return NotFound("Ei ole toodet ");
    }
    var korgehind = _tooted.OrderByDescending(t => t.Price).FirstOrDefault();
    return korgehind!;
}

Prefiksi kasutamine

App.js

import { useEffect, useRef, useState } from 'react';
import './App.css';

function App() {
  const [tooted, setTooted] = useState([]);
  const idRef = useRef();
  const nameRef = useRef();
  const priceRef = useRef();
  const isActiveRef = useRef();
  const [isUsd, setUsd] = useState(false);

  useEffect(() => {
    fetch("https://localhost:4444/api/tooted")
      .then(res => res.json())
      .then(json => setTooted(json));
  }, []);

  function kustuta(index) {
    fetch("https://localhost:4444/api/tooted/kustuta/" + index)
      .then(res => res.json())
      .then(json => setTooted(json));
  }

  function lisa() {
    fetch(`https://localhost:4444/api/tooted/lisa/${Number(idRef.current.value)}/${nameRef.current.value}/${Number(priceRef.current.value)}/${isActiveRef.current.checked}`)
      .then(res => res.json())
      .then(json => setTooted(json));
  }

  function dollariteks() {
    const kurss = 1.1;
    setUsd(true);
    fetch("https://localhost:4444/api/tooted/hind-dollaritesse/" + kurss)
      .then(res => res.json())
      .then(json => setTooted(json));
  }

  function eurodeks() {
    const kurss = 0.9091;
    setUsd(false);
    fetch("https://localhost:4444/api/tooted/hind-dollaritesse/" + kurss)
      .then(res => res.json())
      .then(json => setTooted(json));
  }

  return (
    <div className="App">
      <label>ID</label> <br />
      <input ref={idRef} type="number" /> <br />
      <label>name</label> <br />
      <input ref={nameRef} type="text" /> <br />
      <label>price</label> <br />
      <input ref={priceRef} type="number" /> <br />
      <label>isActive</label> <br />
      <input ref={isActiveRef} type="checkbox" /> <br />
      <button onClick={() => lisa()}>Lisa</button>
      {tooted.map((toode, index) => 
        <div>
          <div>{toode.id}</div>
          <div>{toode.name}</div>
          <div>{toode.price.toFixed(2)}</div>
          <button onClick={() => kustuta(index)}>x</button>
        </div>)}
      {isUsd === false && <button onClick={() => dollariteks()}>Muuda dollariteks</button>}
      {isUsd === true && <button onClick={() => eurodeks()}>Muuda eurodeks</button>}
    </div>
  );
}

export default App;

Lae alla Postman

Program.cs

using veeb_TARpv23.Controllers;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpClient();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseCors(options => options
    .WithOrigins("http://localhost:3000")
    .AllowAnyMethod()
    .AllowAnyHeader()
);

app.UseAuthorization();

app.MapControllers();

app.Run();

ParcelMachineController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace veeb_TARpv23.Controllers
{
    [Route("[controller]")]
    [ApiController] 
    public class ParcelMachineController : ControllerBase
    {
        private readonly HttpClient _httpClient;

        public ParcelMachineController(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        [HttpGet]
        public async Task<IActionResult> GetParcelMachines()
        {
            var response = await _httpClient.GetAsync("https://www.omniva.ee/locations.json");
            var responseBody = await response.Content.ReadAsStringAsync();
            return Content(responseBody, "application/json");
        }
    }
}

App.js

import { useEffect, useState } from 'react';
import './App.css';

function App() {
  const [pakiautomaadid, setPakiautomaadid] = useState([]);
  // Saame Omniva postiautomaadid
  useEffect(() => {
    fetch("https://localhost:4444/parcelmachine")
      .then(res => res.json())
      .then(json => setPakiautomaadid(json));
  }, []);

  return (
    <div className="App">
      <select>
        {pakiautomaadid.map(automaat => 
            <option>
                {automaat.NAME}
            </option>)}
      </select>
    </div>
  );
}

export default App;

NordpoolController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;

namespace veeb_TARpv23.Controllers
{
    [Route("api/[controller]")]
    [ApiController] 
    public class NordpoolController : ControllerBase
    {
        private readonly HttpClient _httpClient;

        public NordpoolController(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }
        [HttpGet("{country}/{start}/{end}")]
        public async Task<IActionResult> GetNordPoolPrices(
            string country, 
            string start, 
            string end)  
        {
            var response = await _httpClient.GetAsync(
                $"https://dashboard.elering.ee/api/nps/price?start={start}&end={end}");
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);

            var jsonDoc = JsonDocument.Parse(responseBody);
            var dataProperty = jsonDoc.RootElement.GetProperty("data");

            string prices;

            switch (country)
            {
                case "ee":
                    prices = dataProperty.GetProperty("ee").ToString();
                    Console.WriteLine(responseBody);

                    return Content(prices, "application/json");
                case "lv":
                    prices = dataProperty.GetProperty("lv").ToString();
                    return Content(prices, "application/json");
                case "lt":
                    prices = dataProperty.GetProperty("lt").ToString();
                    return Content(prices, "application/json");
                case "fi":
                    prices = dataProperty.GetProperty("fi").ToString();
                    return Content(prices, "application/json");
                default:
                    return BadRequest("Invalid country code.");
            }
        }
    }
}

Makse

PaymentController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace veeb_TARpv23.Controllers
{
    [Route("api/[controller]")]
    [ApiController] 
    public class PaymentController : ControllerBase
    {
        private readonly HttpClient _httpClient;

        public PaymentController(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }
        [HttpGet("{sum}")]
        public async Task<IActionResult> MakePayment(string sum)
        {
            var paymentData = new
            {
                api_username = "e36eb40f5ec87fa2", 
                account_name = "EUR3D1", 
                amount = sum,  
                order_reference = Math.Ceiling(new Random().NextDouble() * 999999),  
                nonce = $"a9b7f7e7as{DateTime.Now}{new Random().NextDouble() * 999999}", 
                timestamp = DateTime.Now, 
                customer_url = "https://maksmine.web.app/makse" 
            };

            var json = JsonSerializer.Serialize(paymentData);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "ZTM2ZWI0MGY1ZWM4N2ZhMjo3YjkxYTNiOWUxYjc0NTI0YzJlOWZjMjgyZjhhYzhjZA==");
            var response = await client.PostAsync("https://igw-demo.every-pay.com/api/v4/payments/oneoff", content);
            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                var jsonDoc = JsonDocument.Parse(responseContent);
                var paymentLink = jsonDoc.RootElement.GetProperty("payment_link");
                return Ok(paymentLink);
            }
            else
            {
                return BadRequest("Payment failed.");
            }
        }
    }
}