Python code interacting with the rest API

Please help me revise the code of a simple python function interacting with the Rest API

def submit_notebook():
    job_submit_url = "some_url"
    authorization_header = "Some token"
    path = "some_path"
    temp_run_id_file = "file_name"
    submit_response = requests.post(url=job_submit_url, json=job_submit_dict,
                                    headers={"Content-Type": "application/json", "Authorization": authorization_header})
    if submit_response.status_code == 200:
        submit_response_json = submit_response.json()
        if "run_id" in submit_response_json:
            run_id = submit_response_json("run_id")
            logging.info("Run ID is:" + str(run_id))
            with open(path + temp_run_id_file, 'w') as file:
                file.write(str(run_id))
            return run_id
        else:
            logging.info(json.dumps(submit_response_json.json()))
            raise Exception("Got a bad response.")

Missing delivery address in Rest / V1 / Orders API

One of our suppliers tells us that the return from our rest API / V1 / orders does not contain the delivery address fields. We use Magento 2.3.4. Is this a Magento bug? Which code library should I look for to fix this problem? We need the delivery address to be displayed on this endpoint.

What will cause the Woocommerce REST API to issue 401

https://www.example.com/wp-json/wc/v3/orders?consumer_key=123&consumer_secret=abc works when entered in the browser but fails with CURL with error
{"code": "woocommerce_rest_cannot_view", "message": "Sorry, you cannot list the resources.", "data": {"status": 401}}

Create media via the REST API from an Android app

I do not know if this message will be considered a duplicate because it is the same on stackoverflow.com.

I am trying to upload a file to WordPress using the REST API. I have tried different headers, values ​​but no luck. I have tried different clients such as okhttp and customized as Fast-AndroidNetworking.

I managed to create a new message with AndroidNetworking, but when it comes to creating / downloading new media, it does not work and does not return any response.

While doing this post I was also doing tests, I understood that the WordPress REST API only rejects images, I could download other files like pdf, wav and text. With the second code mention below, I could download a txt file, but when I download a large file, it generates an unknown error. The million question, if there is a problem with WordPress, how PostMan is able to POST media without a problem.

Track my code with AndroidNetworking.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnImage = findViewById(R.id.button);

        btnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 1234);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImageView imgTestImage = findViewById(R.id.imageView1);
        final TextView txtTestPath = findViewById(R.id.txtTestPath);

        if (resultCode == Activity.RESULT_OK)
            switch (requestCode){
                case 1234:
                    Uri uriSelectedImage = data.getData();
                    String imgFullPath = uriSelectedImage.getPath();

                    String imgPath = imgFullPath.substring(imgFullPath.lastIndexOf(":")+1);

                    File imgFile = new File(imgPath);
                    String imgName = imgFile.getName();
                    long imgSize = imgFile.length();
                    String mimType = getContentResolver().getType(uriSelectedImage);

                    txtTestPath.setText(imgPath +"n"+mimType + "n"+ imgName + " "+ String.valueOf(imgSize));


                    AndroidNetworking.initialize(getApplicationContext());
                    AndroidNetworking.post("https://test.matjri.com/wp-json/wp/v2/media")
                            .addFileBody(imgFile)
                            .addHeaders("Connection", "keep-alive")
                            .addHeaders("Host", "test.matjri.com")
                            .addHeaders("Content-Length", String.valueOf(imgSize))
                            .addHeaders("Cache-Control", "no-cache")
                            .addHeaders("Content-Type", mimType)
                            .addHeaders("Content-Disposition", "attachment;filename="" + imgName + """)
                            .addHeaders("Authorization", "Bearer mytoken")
                            .setTag("uploadFile")
                            .setPriority(Priority.MEDIUM)
                            .build()
                            .getAsJSONObject(new JSONObjectRequestListener() {

                                @Override
                                public void onResponse(JSONObject response) {
                                    txtTestPath.setText(response.toString());
                                }
                                @Override
                                public void onError(ANError anError) {

                                    txtTestPath.setText(anError.getMessage());
                                }
                            });




                    imgTestImage.setImageURI(uriSelectedImage);
            }
    }
}

I have also tried the okhttp instead of AndroidNetworking still no luck to download, however, I am getting unknown errors.

The code with okhttp

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnImage = findViewById(R.id.button);

        btnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 1234);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImageView imgTestImage = findViewById(R.id.imageView1);
        final TextView txtTestPath = findViewById(R.id.txtTestPath);

        if (resultCode == Activity.RESULT_OK)
            switch (requestCode){
                case 1234:
                    Uri uriSelectedImage = data.getData();
                    String imgFullPath = uriSelectedImage.getPath();

                    String imgPath = imgFullPath.substring(imgFullPath.lastIndexOf(":")+1);

                    File imgFile = new File(imgPath);
                    String imgName = imgFile.getName();
                    long imgSize = imgFile.length();
                    String mimType = getContentResolver().getType(uriSelectedImage);

                    txtTestPath.setText(imgPath +"n"+mimType + "n"+ imgName + " "+ String.valueOf(imgSize));
                    OkHttpClient okHttpClient = new OkHttpClient();

                    MultipartBody.Builder builder = new MultipartBody.Builder();
                    builder.setType(MultipartBody.FORM);
                    builder.addFormDataPart("file", imgPath);

                    String url = "https://test.matjri.com/wp-json/wp/v2/media/";
                    RequestBody fileBody = RequestBody.create(MediaType.parse(mimType), imgPath);
                    builder.addFormDataPart("file", imgName, fileBody);
                    RequestBody requestBody = builder.build();
                    Request request = new Request.Builder()
                            .url(url)
                            .addHeader("Authorization", "Bearer  mytoken")
                            .addHeader("Content-Type", mimType)
                            .addHeader("Content-Length", String.valueOf(imgSize))
                            .addHeader("Content-Disposition", "attachment; filename="maroof.png"")
                            .post(requestBody)
                            .build();
                    okHttpClient.newCall(request).enqueue(new okhttp3.Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("OkHttp1", "onFailure: "+e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            ResponseBody body = response.body();
                            if (body != null) {
                                txtTestPath.setText(body.string());
                            } else {
                                Log.e("OkHttp1", "onResponse: null");
                            }
                        }
                    });


                    imgTestImage.setImageURI(uriSelectedImage);
            }
    }
} 

With PostMan, the media is downloaded without any problems, and here is the code generated from PostMan.

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("file","/C:/Users/Abdul/OneDrive - OkamKSA/Alahdal/Personal/Web/SS/maroof.png",
    RequestBody.create(MediaType.parse("application/octet-stream"),
    new File("/C:/Users/Abdul/OneDrive - OkamKSA/Alahdal/Personal/Web/SS/maroof.png")))
  .build();
Request request = new Request.Builder()
  .url("https://test.matjri.com/wp-json/wp/v2/media")
  .method("POST", body)
  .addHeader("Authorization", "Bearer mytoken")
  .addHeader("Cookie", "wp-wpml_current_admin_language_d41d8cd98f00b204e9800998ecf8427e=ar; _mcnc=1")
  .build();
Response response = client.newCall(request).execute();

rest – API issues when uploading image, empty file, or corrupted image

Here is what I am trying to accomplish.

I am working on a web integration application which allows our technicians to extract data from our GRC and our share point.

What I would like to be able to do is display images contained in sharepoint in this web application. I think I have 2 choices.

  1. I can programmatically create anonymous links to these images and then call them online.

  2. Pull them down locally and display them that way.

Since there are only a few images, I lean towards 2. So, what I don't understand is how to remove them because they are binary.

I use the shareplum library. I can easily expand a text file like:

from shareplum import Site
from shareplum import Office365
from shareplum.site import Version

server_url = "https://xxx.sharepoint.com/"
site_url = "sites/Technicians/"

un = "un"
pw = "pw"

authcookie = Office365(server_url, username=un, password=pw).GetCookies()
site = Site(server_url + site_url, version=Version.v2016, authcookie=authcookie)

folder = site.Folder('Shared Documents/Technical client documentation' 
                     '/Clients/Company Name, Inc/System Information')
p = folder.get_image('test.jpg')

So from the library we have.

def get_file(self, file_name):
    response = self._session.get(self.site_url + f"/_api/web/GetFileByServerRelativeUrl('{self.info('d')('ServerRelativeUrl')}/{file_name}')/$value")
    return response.text

I added my own function:

def get_image(self, file_name):
    response = self._session.get(self.site_url + f"/_api/web/GetFileByServerRelativeUrl('{self.info('d')('ServerRelativeUrl')}/{file_name}')/$value")
    print(response)
    if response.status_code== 200:
        with open('/home/bruce/test_scripts/pictestNew.jpg', 'wb') as f:
            #response.raw.decode_content = True
            shutil.copyfileobj(response.raw, f)
    return "ok"

I am stuck trying to save the image. The above code gets me empty files. I also tried to return response.text doing it:

p = folder.get_image('test.jpg')
p = bytearray(p)

P would be the response returned.text then:

with open('picOut1.jpg', 'wb') as f:
    f.write(p)

This gives me an image file of the right size but throws a:

Error interpreting the JPEG image file (not a JPEG file: starts with 0xef
0xbf

I also posted this on Stackoverflow. (StackOverflow question, I know it is frowned upon, but my reasoning is as follows. Here, I hope someone can tell me if I am even able to do what I want. The other is just to do I'm not on the python. Honestly, I don't know where the problem is right now.

This is my first race with python and I guess I am doing something wrong here. Would it be easier to create a public link to this image?

rest – Spring, Kafka and Mongo how to create a RestController

I am learning to use Kafka, I have never used anything similar in the past. In my work, I had to create a POC using it and integrate it with Spring Boot and record information on MongoDB (because we will have to retrieve information on demand and I thought it would be the best approach) .

On the consumer side, I created an app, but I don't know if I should have a @RestController class or it's something that should go into Kafka and how.

Right now the code is working but I would like to improve it, especially the Controller part and any additional comments you could make to improve this.

Here is the structure of my project:

enter description of image here

KafkaConfigurator

package com.example.demo.config;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.support.serializer.JsonDeserializer;

import com.example.demo.model.User;

@EnableKafka
@Configuration
public class KafkaConfiguration {
    @Bean
    public ConsumerFactory consumerFactory() {
        Map config = new HashMap();

        config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        config.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id");
        config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

        return new DefaultKafkaConsumerFactory<>(config);
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory();
        factory.setConsumerFactory(consumerFactory());
        return factory; 
    }

    @Bean
    public ConsumerFactory userConsumerFactory() {
        Map config = new HashMap();

        config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        config.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id");
        config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);

        return new DefaultKafkaConsumerFactory<>(config, new StringDeserializer(), new JsonDeserializer<>(User.class));
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory userKafkaListenerFactory() {
        ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(userConsumerFactory());
        return factory; 
    }
}

MyRestController

package com.example.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.listener.KafkaConsumer;
import com.example.demo.model.User;

@RestController
@RequestMapping(value = "users")
public class MyRestController {
    @Autowired
    private KafkaConsumer consumer;

    @GetMapping(path = "/findUserByOffset/{offset}")
    public User getUserByOffset(@PathVariable("offset") Long offset) {
        return consumer.getUserByOffset(offset);
    }

    @GetMapping(path = "/findUsersInRange/{lowerOffset}/{upperOffset}")
    public List getUsersByOffsetRange(@PathVariable("lowerOffset") Long lowerOffset, @PathVariable("upperOffset") Long upperOffset) {
        return consumer.getUsersByOffsetRange(lowerOffset, upperOffset);
    }
}

UserRepository

package com.example.demo.factory;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

import com.example.demo.model.User;

public interface UserRepository extends MongoRepository{
    User findById(String id);
    User findByOffset(Long offset);

    @Query("{'offset' : { $gte: ?0, $lte: ?1 }}")
    List findInOffsetRange(Long lowerOffset, Long upperOffset);
}

KafkaConsumer

package com.example.demo.listener;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import com.example.demo.factory.UserRepository;
import com.example.demo.model.User;

@Service
public class KafkaConsumer {
    @Autowired
    UserRepository userRepository;

    @KafkaListener(topics = "Kafka_Example", groupId = "group_id")
    public void consume(String message) {
        System.out.println("Consumed message: " + message);
    }

    @KafkaListener(topics = "Kafka_Example_json", groupId = "group_json", containerFactory = "userKafkaListenerFactory")
    public void consumeJson(User user) {
        System.out.println("Consumed JSON message: " + user);
        userRepository.save(user);
    }

    public User getUserByOffset(Long offset) {
        return userRepository.findByOffset(offset);
    }

    public List getUsersByOffsetRange(Long lowerOffset, Long upperOffset) {
        return userRepository.findInOffsetRange(lowerOffset, upperOffset);
    }
}

User

package com.example.demo.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class User {
    @Id
    private String id;
    private String name;
    private String dept;
    private Long salary;
    private Long offset;

    public User(String id, String name, String dept, Long salary, Long offset) {
        super();
        this.id = id;
        this.name = name;
        this.dept = dept;
        this.salary = salary;
        this.offset = offset;
    }

    public User() {
        super();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDept() {
        return dept;
    }

    public void setDept(String dept) {
        this.dept = dept;
    }

    public Long getSalary() {
        return salary;
    }

    public void setSalary(Long salary) {
        this.salary = salary;
    }

    public Long getOffset() {
        return offset;
    }

    public void setOffset(Long offset) {
        this.offset = offset;
    }

    @Override
    public String toString() {
        return "User (name=" + name + ", dept=" + dept + ", salary=" + salary + ")";
    }
}

KafkaConsumerDemoApplication

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class KafkaConsumerDemoApplication {

    public static void main(String() args) {
        SpringApplication.run(KafkaConsumerDemoApplication.class, args);
    }

}

application.properties

#server
server.port=8081

#mongodb
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=app1

#logging
logging.level.org.springframework.data=debug
logging.level.=error

pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.5.RELEASE
         
    
    com.example
    kafka-consumer-demo
    0.0.1-SNAPSHOT
    kafka-consumer-demo
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        
        
        
            org.springframework.boot
            spring-boot-starter-web
            2.2.6.RELEASE
        

        
            org.springframework.kafka
            spring-kafka
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
        
            org.springframework.kafka
            spring-kafka-test
            test
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
        
        
        
            org.springframework.data
            spring-data-mongodb
            2.2.6.RELEASE
        


    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


blockchain – Rest API for the transaction

I would like to create an application (java, spring) which returns information on a given transaction for a given txid (and vout specific). I would like it to work for mainnet and testnet. I'm looking for an API that does this.

For example, I wanted to use it to get this information:

https://rest.bitcoin.com/v3-alpha/blockchain/getTxOut/{txid{/{vout}

but it sucks me all the time. Is there such an API?

Should the rest of the world follow the Swedish example of "doing nothing" about coronavirus?

Since the case fatality rates in Sweden are higher than elsewhere in Scandinavia, I guess not.

This article does not include it, but others do.

To date, these are the figures for the Scandinavian countries:

Sweden (10.3 million inhabitants) – 4,435 confirmed cases, 180 deaths. 4.05% mortality rate. 1.75 deaths per 100,000 population.

Denmark (5.8 million inhabitants) – 2,815 cases, 90 deaths. 3.19% mortality. 1.55 deaths per 100,000.

Norway (5.3 million inhabitants) – 4,620 cases, 39 deaths. Mortality rate of 0.84%. 0.74 deaths per 100,000.

Finland (5.52 million inhabitants) – 1,384 cases, 17 deaths. 1.22% mortality. 0.3 deaths per 100,000.

Iceland (pop. 364,260) – 1,135 cases, 3 deaths. 0.26% mortality rate. 0.83 deaths per 100,000.

——-

By comparing:

Italy (60.3 million inhabitants) – 12,428 deaths. 20.6 / 100,000

Spain (46.7 million inhabitants) – 8,464 deaths. 18.1 / 100,000

United States (328.2 million inhabitants) – 3,415 deaths. 1.04 deaths per 100,000.

dnd 5th – Can a character rest under the Ethereal spell?

The etherity lasts 8 hours and does not require concentration:

You are entering the border regions of the ethereal plane, in the area where it overlaps your current plan. You stay in the ethereal border for the duration or until you use your action to cast the spell …

A short rest is:

… a period of stop, of at least 1 hour, during which a character does nothing more painful than eating, drinking, reading and treating his wounds.

During this time, a long rest is:

… a prolonged period of unavailability, of at least 8 hours, during which a character sleeps or exercises a light activity: reading, speaking, eating or standing for at most 2 hours.

If I did nothing for an hour on the ethereal plane, could that count as a short rest? Likewise, if I did nothing for the full 8 hours, would that count as a long rest?

REST API Obtain product information based on the name Magento 1.9

I have created a custom module but I can't seem to get products based on the name of the categories. If I pass only one name, it works.

app / etc / modules / Custom_Restapi.xml



    
        
            true
            local
            
                Mage_Api2
            
        
    

app / code / local / custom / Restapi / config.xml


    
        
            0.1.0
        
    
    
        
            
                Custom_Restapi_Model
            
        
    

application / code / local / custom / Restapi / api2.xml



    
        
            
                Rest API For Auctions
                10
            
        
        
            
                custom_restapi
                custom_restapi/api2_restapi
                Similar Machines API
                10
                
                    
                        1
            1
                    
                
                
                
                    
                        /similar-machines/:name
                        collection
                    
                
                1
            
        
    

app / code / local / custom / Restapi / model / Api2 / Restapi.php

application / code / local / custom / Restapi / model / Api2 / Restapi / Rest / Guest / V1.php

protected function _retrieveCollection($categoriesData)
{
    $cur_category = $fetchIds = $info = $names = array();
    $categoryName = $this->getRequest()->getParam('name');
    if (strpos($categoryName, "https://magento.stackexchange.com/#") !== false) {
        $names = explode("https://magento.stackexchange.com/#",$categoryName);
    }
    else{
        $names() = $categoryName;
    }
    $storeId = Mage::app()->getStore()->getStoreId();
    $_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', array('in'=>$names));

    if($_category->count() > 0)
    {
        foreach ($_category as $cateInfo)
        {
            $fetchIds() = $cateInfo->getEntityId();
        }

        $collection =
            Mage::getResourceModel('catalog/product_collection')
                ->setStoreId($storeId)
                ->addFieldToFilter('status',Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                ->joinField('category_id', 'catalog/category_product', 'category_id',
                    'product_id=entity_id', null, 'left')
                ->joinField('is_in_stock', 'cataloginventory/stock_item', 'is_in_stock', 'product_id=entity_id', 'is_in_stock=1', '{{table}}.stock_id=1', 'left')
                ->addAttributeToFilter('category_id', array('in' => $fetchIds))
                ->addAttributeToSelect(array('entity_id','sku','name','url_path','short_description','status','image','is_in_stock'));
        $collection->getSelect()->group('entity_id')->distinct(true);

        $collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
        $collection->getSelect()->limit(30);

        if($collection->count() > 0)
        {
            foreach($collection as $product)
            {
                $productId = $product->getEntityId();
                //$img = $model->getAttributeRawValue($productId, 'thumbnail', $storeId);
                $info('data')($productId)('id') = $productId;
                $info('data')($productId)('name') = $product->getShortDescription();
                $info('data')($productId)('alt_name') = $product->getName();
                $info('data')($productId)('url') = Mage::getBaseUrl().$product->getUrlPath();
                $info('data')($productId)('img_info') = Mage::getModel('catalog/product_media_config')
                ->getMediaUrl($product->getImage());
            }
            $info('status') = "success";
            $info('has_data') = 1;
        }
        else{
            $info('data') = array();
            $info('status') = "success";
            $info('has_data') = 0;
        }
    }
    else{
        $info('data') = array();
        $info('status') = "success";
        $info('has_data') = 0;
    }

    $cur_category() = $info;

return json_encode($cur_category);
}


/*public function _create(array $data) {
    $categories = $data('categories');
    $collection =
            Mage::getResourceModel('catalog/product_collection')
                ->setStoreId($storeId)
                ->addFieldToFilter('status',Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                ->joinField('category_id', 'catalog/category_product', 'category_id',
                    'product_id=entity_id', null, 'left')
                ->joinField('is_in_stock', 'cataloginventory/stock_item', 'is_in_stock', 'product_id=entity_id', 'is_in_stock=1', '{{table}}.stock_id=1', 'left')
                ->addAttributeToFilter('category_id', array('in' => $categories))
                ->addAttributeToSelect(array('entity_id','sku','name','url_path','short_description','status','image','is_in_stock'));
        $collection->getSelect()->group('entity_id')->distinct(true);

        $collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
        $collection->getSelect()->limit(30);

        return json_encode($collection);
}*/

}

I have to pass the category table to get the product collection
API: http://127.0.0.1/api/rest/products-info/
I want to convert to a post-rest API because the category names can contain space. What I need to improve in this code.