CodeIgniter Forums
Problems with POST in RestFul API - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Problems with POST in RestFul API (/showthread.php?tid=79627)



Problems with POST in RestFul API - wspock - 07-09-2021

Hi guys... I'm working on an API that will upload files. Everything was working fine so far and I have no idea what I did wrong (I was working with cookies and did a 'git pull'). Now when I ask for the POST method, it redirects to my 'Home' controller. Greatful.


RE: Problems with POST in RestFul API - includebeer - 07-09-2021

Compare with your previous commit and you will find what you did wrong!  Tongue

Maybe you messed your Routes.php?


RE: Problems with POST in RestFul API - wspock - 07-09-2021

(07-09-2021, 02:13 PM)includebeer Wrote: Compare with your previous commit and you will find what you did wrong!  Tongue

Maybe you messed your Routes.php?
I work locally Hahaha. I just went to lunch and when I came back it wasn't working.
I've a bad day =/


RE: Problems with POST in RestFul API - wspock - 07-10-2021

(07-09-2021, 02:13 PM)includebeer Wrote: Compare with your previous commit and you will find what you did wrong!  Tongue

Maybe you messed your Routes.php?

Greetings. I found that this happens when I enable the CSRF filter (I need to implement token).


RE: Problems with POST in RestFul API - includebeer - 07-11-2021

(07-10-2021, 05:04 AM)wspock Wrote: Greetings. I found that this happens when I enable the CSRF filter (I need to implement token).

Yes, the CSRF filter does a redirect when the token is not valid:
PHP Code:
redirect()->back()->with('error'$e->getMessage()); 

You can display that error on your page like this:
PHP Code:
<?php if (session('error') !== null) : ?>
<?= session
('error'?>
<?php 
endif; ?>



RE: Problems with POST in RestFul API - paliz - 07-11-2021

hi look my code you should send formData() to upload file via resful api 
read this for uplaod file vi put request  too 
https://codeigniter.com/user_guide/incoming/methodspoofing.html
PHP Code:
<?php
namespace Modules\Common\Controllers;


use 
Modules\Common\Entities\AdvertisementMediaEntity;

use 
Modules\Common\Libraries\CustomFileSystem;
use 
Modules\Common\Models\AdvertisementMediaModel;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Modules\Shared\Controllers\ApiController;


class 
AdvertisementMedia extends ApiController
{


    /**
    * index function
    * @method : GET
    */
    public function index()
    {

        $advertisementMediaModel = new AdvertisementMediaModel();

        $result $advertisementMediaModel->select($this->urlQueryParam->getFiled())
            ->whereIn($this->urlQueryParam->extractQueryKey('in'), $this->urlQueryParam->extractQueryValue('in'))
            ->whereNotIn($this->urlQueryParam->extractQueryKey('nin'), $this->urlQueryParam->extractQueryValue('nin'))
            ->orWhereIn($this->urlQueryParam->extractQueryKey('oin'), $this->urlQueryParam->extractQueryValue('oin'))
            ->orWhereNotIn($this->urlQueryParam->extractQueryKey('onin'), $this->urlQueryParam->extractQueryValue('onin'))
            ->where($this->urlQueryParam->extractQueryArray('whr'))
            ->orWhere($this->urlQueryParam->extractQueryArray('owr'))
            ->like($this->urlQueryParam->extractQueryArray('lik'))
            ->orLike($this->urlQueryParam->extractQueryArray('olk'))
            ->orderBy($this->urlQueryParam->getSort(), $this->urlQueryParam->getOrder())
            ->paginate($this->urlQueryParam->getLimit(), 'default'$this->urlQueryParam->getPage(), $this->urlQueryParam->getOffset());



        return $this->respond([
            'data' => $result,
            'pager' => $advertisementMediaModel->pager->getDetails()
        ], ResponseInterface::HTTP_OKlang('Shared.api.receive'));

    }

    /**
    * show function
    * @method : GET with params ID
    */
    public function show($id null)
    {
        $advertisementMediaModel = new AdvertisementMediaModel();


        return $this->respond([

            'data' => $advertisementMediaModel->where('id'$id)->paginate(1'default'),
            'pager' => $advertisementMediaModel->pager->getDetails()
        ], ResponseInterface::HTTP_OK,  lang('Shared.api.receive'));


    }

    /**
    * create function
    * @method : POST
    */
    public function create()

    {


        $advertisementMediaModel = new AdvertisementMediaModel();
        $customConfig = new \Modules\Common\Config\ModuleCommonConfig();
        $imageService =    \CodeIgniter\Config\Services::image();
        $advertisementMediaEntity = new AdvertisementMediaEntity();


        if ($this->request->getPost()) {

            $rules = [
                'image' => 'uploaded[image]|max_size[image,4096]|ext_in[image,png,jpg,mp4,gif,webp]',

            ];
            if (!$this->validate($rules)) {

                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_ACCEPTABLElang('Shared.api.validation'));

            }

            $advertisementMediaEntity->advertisement_id $this->request->getPost('advertisement_id');

            if (isset($_FILES['image'])) {

                foreach ($this->request->getFileMultiple('image') as $avatar) {


                    $avatar->move($customConfig->uploadDirectory '/advertisement'time() . '.' $avatar->getClientExtension());


                    $advertisementMediaEntity->path $avatar->getName();
                    $advertisementMediaEntity->editPath($avatar->getExtension() != 'mp4');

                    if (!$advertisementMediaModel->save($advertisementMediaEntity)) {

                        return $this->respond([
                            'error' => $advertisementMediaModel->errors(),
                            'success' => false,
                        ], ResponseInterface::HTTP_BAD_REQUEST,  lang('Shared.api.reject'));

                    }
                }


            }


            return $this->respond([
                'data' => ''
            ], ResponseInterface::HTTP_CREATEDlang('Shared.api.save'));

        }

    }

    /**
    * update function
    * @method : PUT or PATCH
    */
    public function update($id null)
    {


        $advertisementMediaModel = new AdvertisementMediaModel();
        $customConfig = new \Modules\Common\Config\ModuleCommonConfig();
        $imageService =    \CodeIgniter\Config\Services::image();
        $handy = new CustomFileSystem();
        $advertisementMediaEntity = new AdvertisementMediaEntity();
        $adsMedia null;

        if ($this->request->getPost()) {

            $rules = [
                'image' => 'uploaded[image]|max_size[image,4096]|ext_in[image,png,webp,jpeg,jpg,mp4,gif]',

            ];

            if (!$this->validate($rules)) {

                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false,
                ], ResponseInterface::HTTP_NOT_ACCEPTABLElang('Shared.api.validation') );

            }


            $adsMedia $advertisementMediaModel->where('id'$id)->first();

            if (is_null($adsMedia)) {
                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_FOUNDlang('Shared.api.exist'));
            }

            $advertisementMediaEntity->id $id;
            $advertisementMediaEntity->advertisement_id $adsMedia->advertisement_id;
            if (isset($_FILES['image'])) {

                foreach ($this->request->getFileMultiple('image') as $avatar) {

                    if ($avatar->getExtension() == 'mp4')
                        $avatar->move($customConfig->uploadDirectory '/advertisement/video'time() . '.' $avatar->getClientExtension());
                    else
                        $avatar->move($customConfig->uploadDirectory '/advertisement/image'time() . '.' $avatar->getClientExtension());

                    $advertisementMediaEntity->path $avatar->getName();

                    $advertisementMediaEntity->editPath($avatar->getExtension() != 'mp4');

                    if (!$advertisementMediaModel->update($id$advertisementMediaEntity)) {

                        return $this->respond([
                            'error' => $advertisementMediaModel->errors(),
                            'success' => false,

                        ], ResponseInterface::HTTP_BAD_REQUEST,  lang('Shared.api.reject'));

                    }
                }


            }


            $handy->removeSingleFile(ROOTPATH $adsMedia->path);

            return $this->respond([
                'data' => array(['id' => $id,
                    'advertisement_id' => $adsMedia->advertisement_id,
                    'path' => $advertisementMediaEntity->path])
            ], ResponseInterface::HTTP_OK,  lang('Shared.api.update'));
        }

    }

    /**
    * edit function
    * @method : DELETE with params ID
    */
    public function delete($id null)
    {


        $advertisementMediaModel = new AdvertisementMediaModel();
        $handy = new CustomFileSystem();
        $id = ($id == $id);

        if ($id == 0) {

            $isExist $advertisementMediaModel->where(['advertisement_id' => $this->urlQueryParam->getForeignKey()])->
            findAll();
            $target = array('advertisement_id' => $this->urlQueryParam->getForeignKey());
        } else {
            $isExist $advertisementMediaModel->where(['id' => $id])->findAll();
            $target = array('id' => $id);
        }


        if ($isExist) {
            $advertisementMediaModel->where($target)->delete();
            foreach ($isExist as $path) {

                $handy->removeSingleFile(ROOTPATH $path->path);
            }


        }

        return $this->respond([

        ], ResponseInterface::HTTP_OKlang('Shared.api.remove'));

    }