NAV Navbar
Logo
python shell go javascript ruby csharp java

Introduction

Welcome to the NanoNets API!
You can use our API to build custom deep learning models for images.

We have language bindings in Shell, Ruby, Golang, Java, C# and Python! You can view code examples in the dark area to the right, and you can switch the programming language for the examples with the tabs in the top right.

In the documentation, you will find ready to fire code samples in these languages as well as detailed API specs for different endpoints.

Authentication

Make sure to replace REPLACE_API_KEYwith your API key. NanoNets uses HTTP basic Auth for authenticating REST endpoints. Provide your API key as the basic auth username value. You do not need to provide a password. You can register for your API key at our developer portal.

NanoNets expects for the API key to be included in all API requests to the server in a header that looks like the following:

Authorization: REPLACE_API_KEY

All API requests must be made over HTTPS. Calls made over plain HTTP will fail. API requests without authentication will also fail.

Errors

Nanonets uses conventional HTTP response codes as much as possible. We also include details about error in response body.

The 2xx range response codes indicates fully or partially successful response. The 4xx range response codes indicate error in request itself. The 5xx range response codes indicate error from our end in which case you should inform us about it.

Below is JSON structure for error if any included in body to give you additional information about reason for error and instructions to fix or mitigate the error.

The errors object

JSON structure for errors object:


{
  "message": "string",
  "code": "int",
  "errors": [
    {
      "reason": "string",
      "message": "string",
    }
  ]
}
        
Attributes Description
code HTTP response code for error. Could be one of the following:
  • 200: Success
  • 202: Partially successful
  • 400: Bad request. Some parameter missing in request
  • 401: Unauthorized. Check if api key or model id is correct
  • 404: Object does not exists
  • 402: Payment required. Exhausted free API calls. You should visit profile page
  • 500: Internal server error
message More information about error and instructions to fix or mitigate errors
errors JSON array for more details about errors. In case there are multiple errors, each element in array will corrospond to those errors, more information about error and possible fix

Image Categorization

QuickStart

1. Make sure you have correct API key with you

You will need a valid API key to authenticate all API calls. You can create new API keys or revoke existing ones at our API keys page.

You must replace REPLACE_API_KEY in all code samples with key you have created at this page


# Install dependencies using pip
pip install requests
        
No dependencies
No dependencies
No dependencies

# Dependency for multipart request
# https://github.com/nicksieger/multipart-post
gem install multipart-post
        

// Restsharp for HTTP REST API requests- http://restsharp.org/
// To install RestSharp, run the following command in the Package Manager Console
Install-Package RestSharp -Version 105.2.3
        

// Gson for json parsing
// https://mvnrepository.com/artifact/com.google.code.gson/gson/2.7
// Gradle installation:
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'

// Timber for logging
// https://mvnrepository.com/artifact/com.jakewharton.timber/timber/2.2.2
// Gradle installation:
compile group: 'com.jakewharton.timber', name: 'timber', version: '2.2.2'

// OKHTTP3 for http requests
// https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/3.2.0
// Gradle installation:
compile group: 'com.jakewharton.timber', name: 'timber', version: '2.2.2'
        

2. Install dependencies

NanoNets API has REST endpoints that use HTTP Authentication and the response is in JSON format. Errors are communicated using HTTP error codes and have JSON body with a cause for error and steps to fix. So dependencies are mostly HTTP REST clients and JSON parsing libraries if any depending on the language. We have given instructions on the right side for every language to install dependencies.


import requests, json, time, urllib, zipfile

base_url = 'https://app.nanonets.com/api/v2/ImageCategorization'
headers = {
    'accept': 'application/x-www-form-urlencoded'
}

# Step 1: Create a model
print "Step 1: Creating Model"

url = base_url + '/Model/'
data = {'categories' : ['cats', 'dogs']}
response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), data=data)

if response.ok:
  modelId = json.loads(response.text)['model_id']
  print "modelId is: ",modelId
else:
  print('Error in creating model', response.text)

# Step 2: Upload training images in categories
# Downloading images from one of the categories to upload

print "Step 2: Uploading Images"
urllib.urlretrieve('https://s3-us-west-2.amazonaws.com/nanonets/datasets/dog.zip', 'dog.zip')
zip_ref = zipfile.ZipFile('dog.zip', 'r')
zip_ref.extractall('./')
zip_ref.close()

for i in range(50):
  print "uploading image", i
  url = base_url + '/UploadFile/'

  data = {'file':open('./dog/dog_' + str(i) + '.jpg', 'rb'), \
      'category':('', 'dogs'), \
      'modelId':('', modelId)}

  response = requests.post(url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), files=data)
  if not response.ok:
    print "error uploading image", response.text, data

  url = base_url + '/UploadUrls/'

  headers = {
      'accept': 'application/x-www-form-urlencoded'
  }

  data = {'modelId' : modelId, 'category': 'cats', 'urls': ['https://s3-us-west-2.amazonaws.com/nanonets/datasets/cat/cat_' + str(i) + '.jpg']}

  response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), data=data)
  if not response.ok:
    print "error uploading image", response.text, data

# Step 3:  Now that you have uploaded images, you can start training model
print "Step 3: Training Model"
url = base_url + '/Train/'
querystring = {'modelId': modelId}

headers = {'authorization': 'Basic REPLACE_API_KEY'}

response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), params=querystring)
if not response.ok:
  print "error training model", response.text
# Wait for the model to be trained, check the status of the model

trained = False
while not trained:
  url = base_url + '/Model/'

  querystring = {'modelId': modelId}

  response = requests.request('GET', url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY',''), params=querystring)

  if response.ok:
    model_state = json.loads(response.text)['state']
    if model_state == 5:
        trained = True
        break
    else:
        print('Model status: ', json.loads(response.text)['status'])
        time.sleep(100)
  else:
    print "error getting model status", response.text

#Step 4:  Prediction using url
print "Testing Model"
url = base_url + '/LabelUrls/'

headers = {
    'accept': 'application/x-www-form-urlencoded'
}

data = {'modelId': modelId, 'urls' : ['https://goo.gl/ICoiHc']}

response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), data=data)
print(response.text)

# Prediction using local file
url = base_url + '/LabelFile/'

data = {'file':open('./dog/dog_1.jpg', 'rb'), \
    'modelId': ('', modelId)}

response = requests.post(url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), files=data)
print(response.text)

        

Code samples for quickstart are only available for python, ruby, java and golang for now.
You can see the rest of the documentation for shell queries or see the documentation in one of the other lanuages.
        


package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "mime/multipart"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "time"
    "path/filepath"
    "archive/zip"
    "strings"
    "log"
)

type APIModelCategory struct {
    Name  string `json:"name"`
    Count int    `json:"count"`
}

type APIModel struct {
    ModelId    string             `json:"model_id"`
    ModelType  string             `json:"model_type"`
    State      int                `json:"state"`
    Status     string             `json:"status"`
    Accuracy   float32            `json:"accuracy"`
    Categories []APIModelCategory `json:"categories"`
}

type APIPrediction struct {
    Category     string    `json:category`
    Probability  float32   `json:probability`
}

type APIPredictionResult struct {
    Prediction   []APIPrediction    `json:prediction`
    Input        string             `json:input`
}

type APIResult struct {
    ModelId      string                 `json:model_id`
    Message      string                 `json:message`
    Result       []APIPredictionResult  `json:result`
}

func main() {
    //Step 1:  Create new model
    fmt.Println("Step 1: Creating new model")
    baseUrl := "https://app.nanonets.com/api/v2/ImageCategorization"
    Url := baseUrl + "/Model/"

    data := url.Values{}
    data.Set("categories", "cats")
    data.Add("categories", "dogs")

    fmt.Println("data is: ", data)

    req, err := http.NewRequest("POST", Url, bytes.NewBufferString(data.Encode()))
    if err != nil {
        fmt.Println("Error in creating request", Url)
    }

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println("Error in response", Url)
    }

    if res.StatusCode != http.StatusOK {
        fmt.Println("Error")
        return
    }

    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println("Error in reading response", Url)
    }

    var apiModel APIModel
    json.Unmarshal(body, &apiModel)

    modelId := apiModel.ModelId
    fmt.Println("New model created. Model id is: ", modelId)

    //Step 2: Upload images
    fmt.Println("Step 2: Uploading images in model with id: ", modelId)

    downloadFromUrl("https://s3-us-west-2.amazonaws.com/nanonets/datasets/dog.zip")
    Unzip("dog.zip", "")

    // Upload images for training
    for i := 0; i < 50; i++ {
        fmt.Println("Uploading image ", i)
        Url = baseUrl + "/UploadUrls/"

        data := url.Values{}
        data.Set("modelId", modelId)
        data.Add("category", "cats")
        data.Add("urls", "https://s3-us-west-2.amazonaws.com/nanonets/datasets/cat/cat_" + strconv.Itoa(i) + ".jpg")

        req, err := http.NewRequest("POST", Url, bytes.NewBufferString(data.Encode()))
        if err != nil {
            fmt.Println("Error in creating request", Url)
        }

        req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
        req.SetBasicAuth("REPLACE_API_KEY", "")

        res, err := http.DefaultClient.Do(req)
        if err != nil {
            fmt.Println("Error in response", Url)
        }

        if res.StatusCode != http.StatusOK {
            fmt.Println("Error in uploading image")
        }

        defer res.Body.Close()
        Url = baseUrl + "/UploadFile/"

        file, err := os.Open("dog/dog_" + strconv.Itoa(i) + ".jpg")
        if err != nil {
            fmt.Println("Error in opening file", file)
        }

        defer file.Close()

        body := &bytes.Buffer{}
        writer := multipart.NewWriter(body)

        part, err := writer.CreateFormFile("file", filepath.Base("dog_" + strconv.Itoa(i) + ".jpg"))
        if err != nil {
            fmt.Println("Error in creating request for file upload")
        }

        _, err = io.Copy(part, file)
        if err != nil {
            fmt.Println("Error in copying file into request")
        }

        writer.WriteField("category", "dogs")
        writer.WriteField("modelId", modelId)

        contentType := writer.FormDataContentType()

        err = writer.Close()
        if err != nil {
            fmt.Println("Error in creating request")
        }

        req, err = http.NewRequest("POST", Url, body)
        if err != nil {
            fmt.Println("Error in creating request")
        }

        req.Header.Add("Content-Type", contentType)
        req.SetBasicAuth("REPLACE_API_KEY", "")

        res, err = http.DefaultClient.Do(req)
        defer res.Body.Close()

        if err != nil {
            fmt.Println("Error in response")
        }

        if res.StatusCode != http.StatusOK {
            fmt.Println("Error in uploading image")
        }
    }

    //Step 3: Start model training
    fmt.Println("Step 3: Training Model")
    Url = baseUrl + "/Train/?modelId=" + modelId

    req, err = http.NewRequest("POST", Url, nil)
    if err != nil {
        fmt.Println("Error in creating request", Url)
    }

    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ = http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println("Error in response", Url)
    }

    if res.StatusCode != http.StatusOK {
        fmt.Println("Error")
    }

    defer res.Body.Close()
    body, err = ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println("Error in reading response", Url)
    }

    // Wait till model is trained
    trained := false
    Url = baseUrl + "/Model/?id=" + modelId

    req, err = http.NewRequest("GET", Url, nil)
    if err != nil {
        fmt.Println("Error in creating request", Url)
    }

    req.SetBasicAuth("REPLACE_API_KEY", "")

    for trained == false {
        res, err := http.DefaultClient.Do(req)
        if err != nil {
            fmt.Println("Error in getting response", err)
        }

        if res.StatusCode != http.StatusOK {
            fmt.Println("Error")
        }

        defer res.Body.Close()
        body, err := ioutil.ReadAll(res.Body)
        if err != nil {
            fmt.Println("Error in reading response", err)
        }

        err = json.Unmarshal(body, &apiModel)
        if err != nil {
            fmt.Println("Error in reading response", err)
        }

        if (apiModel.State == 5) {
            trained = true
        } else {
            time.Sleep(100 * time.Second)
        }
    }

    //Step 4:  Label new image using Label api
    fmt.Println("Step 4: Using Model for new Prediction")
    Url = baseUrl + "/LabelUrls/"

    data = url.Values{}
    data.Set("modelId", modelId)
    data.Add("urls", "https://goo.gl/ICoiHc")

    req, err = http.NewRequest("POST", Url, bytes.NewBufferString(data.Encode()))
    if err != nil {
        fmt.Println("Error in creating request", Url)
    }

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, err = http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println("Error in getting response", Url)
    }

    if res.StatusCode != http.StatusOK {
        fmt.Println("Error")
    }

    defer res.Body.Close()
    body, err = ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println("Error in readijng response", Url)
    }

    var result APIResult
    json.Unmarshal(body, &result)

    fmt.Println("Result is: ", result)
}


//Helper functions
//To unzip image dataset
func Unzip(src, dest string) ([]string, error) {

    var filenames []string

    r, err := zip.OpenReader(src)
    if err != nil {
        return filenames, err
    }
    defer r.Close()

    for _, f := range r.File {

        rc, err := f.Open()
        if err != nil {
            return filenames, err
        }
        defer rc.Close()

        // Store filename/path for returning and using later on
        fpath := filepath.Join(dest, f.Name)
        filenames = append(filenames, fpath)

        if f.FileInfo().IsDir() {

            // Make Folder
            os.MkdirAll(fpath, os.ModePerm)

        } else {

            // Make File
            var fdir string
            if lastIndex := strings.LastIndex(fpath, string(os.PathSeparator)); lastIndex > -1 {
                fdir = fpath[:lastIndex]
            }

            err = os.MkdirAll(fdir, os.ModePerm)
            if err != nil {
                log.Fatal(err)
                return filenames, err
            }
            f, err := os.OpenFile(
                fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
            if err != nil {
                return filenames, err
            }
            defer f.Close()

            _, err = io.Copy(f, rc)
            if err != nil {
                return filenames, err
            }

        }
    }
    return filenames, nil
}

//To download files
func downloadFromUrl(url string) {
	tokens := strings.Split(url, "/")
	fileName := tokens[len(tokens)-1]
	fmt.Println("Downloading", url, "to", fileName)

	// TODO: check file existence first with io.IsExist
	output, err := os.Create(fileName)
	if err != nil {
		fmt.Println("Error while creating", fileName, "-", err)
		return
	}
	defer output.Close()

	response, err := http.Get(url)
	if err != nil {
		fmt.Println("Error while downloading", url, "-", err)
		return
	}
	defer response.Body.Close()

	n, err := io.Copy(output, response.Body)
	if err != nil {
		fmt.Println("Error while downloading", url, "-", err)
		return
	}

	fmt.Println(n, "bytes downloaded.")
}

        

Code samples for quickstart are only available for python, ruby, java and golang for now.
You can see the rest of the documentation for javascript or see the documentation in one of the other lanuages.
        


require 'uri'
require 'net/http'
require 'net/http/post/multipart'
require 'json'
require 'active_support/time'

#Step 1: Create new model
url = URI('https://app.nanonets.com/api/v2/ImageCategorization/Model/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["accept"] = 'application/x-www-form-urlencoded'
request.basic_auth 'REPLACE_API_KEY', ''

request.set_form_data({'categories' => ['cats', 'dogs']})

response = http.request(request)
# puts response.read_body

apiModel = JSON.parse(response.read_body)
modelId = apiModel['model_id']
puts("New model created. Model id is #{modelId}")

# Step 2: Upload Images
# Download and extract zip
$i = 0
$num = 50

while $i < $num  do
	# Upload image by url
	puts("Uploading image #$i" )

	url = URI('https://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/')

	http = Net::HTTP.new(url.host, url.port)

	request = Net::HTTP::Post.new(url)
	request["accept"] = 'application/x-www-form-urlencoded'
	request.basic_auth 'REPLACE_API_KEY', ''

	request.set_form_data({'modelId' => modelId, 'category' => 'cats', 'urls' => [ "https://s3-us-west-2.amazonaws.com/nanonets/datasets/cat/cat_" + $i.to_s + ".jpg"]})

	response = http.request(request)

	# Upload image by file
	url = URI('https://app.nanonets.com/api/v2/ImageCategorization/UploadFile/')

	http = Net::HTTP.new(url.host, url.port)

	File.open('dog/dog_' + $i.to_s + '.jpg') do |jpg|
	  request = Net::HTTP::Post::Multipart.new(url.path,
	    'file' => UploadIO.new(jpg, 'image/jpeg', 'dog/dog_' + $i.to_s + '.jpg'),
	    'modelId' => modelId,
	    'category' => 'dogs')
	  request.basic_auth 'REPLACE_API_KEY', ''
	  response = Net::HTTP.start(url.host, url.port) do |http|
	    http.request(request)
	  end
	end

	$i +=1
end


#Step 3: Start model training
url = URI('https://app.nanonets.com/api/v2/ImageCategorization/Train/?modelId=' + modelId)

http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request.basic_auth 'REPLACE_API_KEY', ''
response = http.request(request)

trained = false

url = URI('https://app.nanonets.com/api/v2/ImageCategorization/Model/?id=' + modelId)
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(url)
request.basic_auth 'REPLACE_API_KEY', ''

while trained == false
	response = http.request(request)

	apiModel = JSON.parse(response.read_body)

	if apiModel['state'] == 5
		trained = true
	else
		modelStatus = apiModel['status']
		puts("Model status: #{modelStatus}")
		sleep 2.minutes
	end
end

#Step 4 Predict cateogry for new image using model:
url = URI('https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["accept"] = 'application/x-www-form-urlencoded'
request.basic_auth 'REPLACE_API_KEY', ''

request.set_form_data({'modelId' => modelId, 'urls' => ['https://goo.gl/ICoiHc']})

response = http.request(request)
puts response.read_body

Code samples for quickstart are only available for python, ruby, java and golang for now.
You can see the rest of the documentation for C# or see the documentation in one of the other lanuages.
        


package com.example.nanonets.test;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;

import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import timber.log.Timber;

public class MainActivity extends AppCompatActivity {

    private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpeg");

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

        Timber.d("Inside main activity");

        DownloadFilesTask downloadFilesTask = new DownloadFilesTask();
        downloadFilesTask.execute("");

        Timber.d("task executed");
    }

    class APIPrediction {
        private String Category;
        private float Probability;

        APIPrediction() {

        }
    }

    class APIPredictionResult {
        private APIPrediction[] Prediction;
        private String Input;

        APIPredictionResult() {

        }
    }

    class APIResult {
        private String ModelId;
        private String Message;
        private APIPredictionResult[] Result;

        APIResult() {

        }
    }

    class APIModelCategory {
        private String Name;
        private int Count;

        APIModelCategory() {

        }
    }

    class APIModel {
        private String ModelId;
        private String ModelType;
        private int State;
        private String Status;
        private float Accuracy;
        private APIModelCategory[] Categories;

        APIModel() {

        }
    }

    private class DownloadFilesTask extends AsyncTask<String, Void, Void> {
        @Override
        protected Void doInBackground(String... params) {
            Timber.d("Starting okhttp client");

            Timber.d(getApplication().getFilesDir().getAbsolutePath());

            OkHttpClient client = new OkHttpClient();
            Gson gson = new Gson();
            APIModel apiModel;
            String modelId;

            try {
                RequestBody formBody = new FormBody.Builder()
                        .add("categories", "cats")
                        .add("categories", "dogs").build();

                Request request = new Request.Builder()
                        .url("https://app.nanonets.com/api/v2/ImageCategorization/Model/")
                        .post(formBody)
                        .addHeader("authorization", Credentials.basic("REPLACE_API_KEY", ""))
                        .build();


                Response response = client.newCall(request).execute();
                apiModel = gson.fromJson(response.body().string(), APIModel.class);
                modelId = apiModel.ModelId;

                for (int i = 0; i < 50; i++) {
                    Timber.d("Uploading image " + Integer.toString(i));
                    formBody = new FormBody.Builder()
                            .add("modelId", modelId)
                            .add("category", "cats")
                            .add("urls", "https://s3-us-west-2.amazonaws.com/nanonets/datasets/cat/cat_" + Integer.toString(i) + ".jpg").build();

                    request = new Request.Builder()
                            .url("https://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/")
                            .post(formBody)
                            .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
                            .build();

                    client.newCall(request).execute();

                    RequestBody requestBody = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("modelId", modelId)
                            .addFormDataPart("category", "dogs")
                            .addFormDataPart("file", "dog_" + Integer.toString(i) + ".jpg",
                                    RequestBody.create(MEDIA_TYPE_JPG,
                                            new File(getApplication().getFilesDir(), "/dog/dog_" + Integer.toString(i) + ".jpg")))
                            .build();

                    request = new Request.Builder()
                            .url("http://app.nanonets.com/api/v2/ImageCategorization/UploadFile/")
                            .post(requestBody)
                            .addHeader("Authorization", Credentials.basic("HgAWeTnLZpTSxCKs0gigByk5SH9pmeudGKRHhARdh_P", ""))
                            .build();

                    client.newCall(request).execute();
                }

                request = new Request.Builder()
                        .url("https://app.nanonets.com/api/v2/ImageCategorization/Train/?modelId=" + modelId)
                        .post(null)
                        .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
                        .build();

                client.newCall(request).execute();

                boolean trained = true;

                while (!trained) {
                    request = new Request.Builder()
                            .url("https://app.nanonets.com/api/v2/ImageCategorization/Model/?id=" + modelId)
                            .get()
                            .addHeader("authorization", Credentials.basic("REPLACE_API_KEY", ""))
                            .build();

                    response = client.newCall(request).execute();

                    apiModel = gson.fromJson(response.body().string(), APIModel.class);

                    if (apiModel.State == 5) {
                        Timber.d("Model is trained");
                        trained = true;
                    } else {
                        Timber.d(apiModel.Status);
                        Thread.sleep(120 * 1000);
                    }
                }

                formBody = new FormBody.Builder()
                        .add("modelId", modelId)
                        .add("urls", "https://goo.gl/ICoiHc").build();

                request = new Request.Builder()
                        .url("https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/")
                        .post(formBody)
                        .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
                        .build();

                response = client.newCall(request).execute();

                APIResult apiResult;
                apiResult = gson.fromJson(response.body().string(), APIResult.class);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}

        

3. Run code samples

There are code samples in multiple languages in right pane which will:


Feel free to run code samples and play around with it.

Models

The model object

JSON structure for model object:


[
  {
    "model_id": "string",
    "model_type": "string",
    "state": int
    "categories": [
      {
        "name": "string",
        "count": int
      }
    ]
  }
]
        
Attributes Description
model_id Unique id for the model
model_type Type of model. Possible values are:
  • classification: Image classification model
  • localization: Object detection model
  • textclassification: Text classification model
state Current state of model. Possible values are:
  • -1: Error in model training
  • 0: Model created. No training data uploaded yet
  • 1: Training data uploaded. Need to annotate data
  • 2: Training data annotated. Need to start training
  • 3: Model in training queue
  • 4: Model currently training
  • 5: Model hosted. Can be used for prediction

Get All models for a user


import requests

url = 'https://app.nanonets.com/api/v2/ImageCategorization/Models/'

response = requests.request('GET', url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''))

print(response.text)
        

curl --request GET \
  --url https://app.nanonets.com/api/v2/ImageCategorization/Models/ \
  -u 'REPLACE_API_KEY'

        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ImageCategorization/Models/"

    req, _ := http.NewRequest("GET", url, nil)

    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = null;

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://app.nanonets.com/api/v2/ImageCategorization/Models/");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ImageCategorization/Models/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)
request.basic_auth 'REPLACE_API_KEY', ''

response = http.request(request)
puts response.read_body

        


var client = new RestClient("https://app.nanonets.com/api/v2/ImageCategorization/Models/");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("REPLACE_API_KEY:")));
IRestResponse response = client.Execute(request);

        

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("https://app.nanonets.com/api/v2/ImageCategorization/Models/")
  .get()
  .addHeader("authorization", Credentials.basic("REPLACE_API_KEY", ""))
  .build();

Response response = client.newCall(request).execute();
        

This endpoint returns information of all models created by user.

HTTP Request

GET http://app.nanonets.com/api/v2/ImageCategorization/Models/

Query Parameters

Parameter Default Description
No parameters

The code above returns the model object in the format below:


[
  {
    "model_id": "00000000-0000-0000-0000-000000000000",
    "model_type": "classification",
    "state": 0
    "categories": [
      {
        "name": "category1",
        "count": 0
      },
      {
        "name": "category2",
        "count": 0
      }
    ]
  }
]
        

Response

The code above returns a JSON array of the model object as shown in right side pane populated with default values

Try it live

You can try the api live here

Get a specific model information



import requests

url = 'https://app.nanonets.com/api/v2/ImageCategorization/Model/'

querystring = {'modelId': 'REPLACE_MODEL_ID'}

response = requests.request('GET', url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY',''), params=querystring)

print(response.text)

        

curl --request GET \
  --url 'https://app.nanonets.com/api/v2/ImageCategorization/Model/?id=REPLACE_MODEL_ID' \
  -u 'REPLACE_API_KEY'
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ImageCategorization/Model/?id=REPLACE_MODEL_ID"

    req, _ := http.NewRequest("GET", url, nil)

    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = null;

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://app.nanonets.com/api/v2/ImageCategorization/Model/?id=REPLACE_MODEL_ID");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);

        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ImageCategorization/Model/?id=REPLACE_MODEL_ID')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)

request.basic_auth 'REPLACE_API_KEY', ''

response = http.request(request)
puts response.read_body

        


var client = new RestClient("https://app.nanonets.com/api/v2/ImageCategorization/Model/?id=REPLACE_MODEL_ID");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("REPLACE_API_KEY:")));
IRestResponse response = client.Execute(request);

        


OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("https://app.nanonets.com/api/v2/ImageCategorization/Model/?id=REPLACE_MODEL_ID")
  .get()
  .addHeader("authorization", Credentials.basic("REPLACE_API_KEY", ""))
  .build();

Response response = client.newCall(request).execute();

        

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "classification",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

Response 404: Model does not exists


{
  "message": "Does not exists",
  "code": 404,
  "errors": [
    {
      "reason": "Model does not exists",
      "message": "Check if model id is correct in request"
    }
  ]
}
        

This endpoint retrieves a specific model's details given it's id.

HTTP Request

GET http://app.nanonets.com/api/v2/ImageCategorization/Model/

URL Parameters

Parameter Description
id The ID of the model to retrieve

Errors

You can see the JSON structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
404 Model does not exists Check if you have entered correct model id with valid API key

Try it live

You can try the api live here

Create new model



import requests

url = 'https://app.nanonets.com/api/v2/ImageCategorization/Model/'

headers = {
    'accept': 'application/x-www-form-urlencoded'
}

data = {'categories' : ['category1', 'category2']}

response = requests.request("POST", url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), data=data)

print(response.text)

        


curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ImageCategorization/Model/' \
  --header 'accept: application/x-www-form-urlencoded' \
  -u 'REPLACE_API_KEY' \
  -d 'categories=category1&categories=category2'

          


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
    "bytes"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ImageCategorization/Model/"

    data := url.Values{}
    data.Set("categories", "category1")
    data.Add("categories", "category2")

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = "categories=category1&categories=category2";

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ImageCategorization/Model/");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ImageCategorization/Model/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["accept"] = 'application/x-www-form-urlencoded'
request.basic_auth 'REPLACE_API_KEY', ''

request.set_form_data({'categories' => ['category1', 'category2']})

response = http.request(request)
puts response.read_body
        


var client = new RestClient("https://app.nanonets.com/api/v2/ImageCategorization/Model/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "application/x-www-form-urlencoded");
request.AddParameter("categories", "category1");
request.AddParameter("categories", "category2");
IRestResponse response = client.Execute(request);

        


OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
    .add("categories", "category1")
    .add("categories", "category2").build();

Request request = new Request.Builder()
    .url("https://app.nanonets.com/api/v2/ImageCategorization/Model/")
    .post(formBody)
    .addHeader("authorization", Credentials.basic("REPLACE_API_KEY", ""))
    .build();

Response response = client.newCall(request).execute();
          

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "classification",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

Response 400: Bad request


{
  "message": "Does not exists",
  "code": 404,
  "errors": [
    {
      "reason": "Model does not exists",
      "message": "Check if model id is correct in request"
    }
  ]
}
        

You can create a new model using this endpoint. A successful API call will return the json strcutre of the newly created model. You can then use the model's id to upload images for each category and then retrain the model.

HTTP Request

POST http://app.nanonets.com/api/v2/ImageCategorization/Model/

POST Parameters

Parameter Description
categories Categories for model

Errors

You can see the json structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
400 Zero or One category in request Add two or more categories in parameters

Try it live

You can try the api live here

Upload

Upload training images by url



import requests

url = 'https://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/'

headers = {
    'accept': 'application/x-www-form-urlencoded'
}

data = {'modelId' : 'REPLACE_MODEL_ID', 'category': 'category1', 'urls': ['https://goo.gl/ICoiHc']}

response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), data=data)

print(response.text)
        

curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/' \
  --header 'accept: application/x-www-form-urlencoded' \
  -d 'modelId=REPLACE_MODEL_ID&category=category1&urls=https://goo.gl/ICoiHc' \
  -u 'REPLACE_API_KEY'
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/"

    data := url.Values{}
    data.Set("modelId", "REPLACE_MODEL_ID")
    data.Add("category", "category1")
    data.Add("urls", "https://goo.gl/ICoiHc")

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = 'modelId=REPLACE_MODEL_ID&category=category1&urls=https://goo.gl/ICoiHc';

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["accept"] = 'application/x-www-form-urlencoded'
request.basic_auth 'REPLACE_API_KEY', ''

request.set_form_data({'modelId' => 'REPLACE_MODEL_ID', 'category' => 'category1', 'urls' => ['https://goo.gl/ICoiHc']})

response = http.request(request)
puts response.read_body

        


var client = new RestClient("https://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "application/x-www-form-urlencoded");
request.AddParameter("modelId", "REPLACE_MODEL_ID");
request.AddParameter("category", "category1");
request.AddParameter("urls", "https://goo.gl/ICoiHc");
IRestResponse response = client.Execute(request);
        


OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
        .add("modelId", "REPLACE_MODEL_ID")
        .add("category", "category1")
        .add("urls", "https://goo.gl/ICoiHc").build();

Request request = new Request.Builder()
        .url("https://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/")
        .post(formBody)
        .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
        .build();

Response response = client.newCall(request).execute();
        

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "classification",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

You can use this endpoint to upload training images for a category (for the specified model) by image urls. You can upload multiple images in the same request by adding an array of urls. You will receive model information along with total number of images per category on successful execution.

HTTP Request

POST http://app.nanonets.com/api/v2/ImageCategorization/UploadUrls/

POST Parameters

Parameter Description
modelId Unique id of the model
category Category image belongs to
urls array of urls for images

Errors

You can see the json structure for the error object in right column. Here are possible error codes and reasons.

Code Reason Message
202 Request partially successful One or more urls might not be correct or got no response
404 Model does not exists Check if the model id exists
400 Category not valid for model Check if this model has the category used in the request
400 Urls missing Check if you have included an array of image urls

Try it live

You can try the api live here

Upload training images by file



import requests

url = 'https://app.nanonets.com/api/v2/ImageCategorization/UploadFile/'

data = {'file' :open('REPLACE_IMAGE_PATH.jpg', 'rb'), \
    'category' :('', 'category1'), \
    'modelId' :('', 'REPLACE_MODEL_ID')}

response = requests.post(url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), files=data)

print(response.text)
        

curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ImageCategorization/UploadFile/' \
  --header 'accept: multipart/form-data' \
  -u 'REPLACE_API_KEY' \
  -F 'category=category1' \
  -F 'modelId=REPLACE_MODEL_ID' \
  -F 'file=@REPLACE_IMAGE_PATH.jpg'
        

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ImageCategorization/UploadFile/"

    file, err := os.Open('REPLACE_IMAGE_PATH.jpg')
    if err != nil {
        return nil, err
    }

    defer file.Close()

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    part, err := writer.CreateFormFile("file", filepath.Base("REPLACE_IMAGE_PATH.jpg"))
    if err != nil {
        return nil, err
    }
    _, err = io.Copy(part, file)

    writer.WriteField("category", "category1")
    writer.WriteField("modelId", "REPLACE_MODEL_ID")

    contentType := writer.FormDataContentType()

    err = writer.Close()
    if err != nil {
        return nil, err
    }

    req, _ := http.NewRequest("POST", url, body)

    req.Header.Add("Content-Type", contentType)
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = new FormData();
data.append('category', 'category1');
data.append('modelId', 'REPLACE_MODEL_ID');
data.append('file', 'REPLACE_IMAGE_PATH.jpg');

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ImageCategorization/UploadFile/");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'
require 'net/http/post/multipart'


url = URI('https://app.nanonets.com/api/v2/ImageCategorization/UploadFile/')

http = Net::HTTP.new(url.host, url.port)

File.open('REPLACE_IMAGE_PATH.jpg') do |jpg|
  request = Net::HTTP::Post::Multipart.new(url.path,
    'file' => UploadIO.new(jpg, 'image/jpeg', 'REPLACE_IMAGE_PATH.jpg')
    'modelId' => 'REPLACE_MODEL_ID',
    'category' => 'category1')
  request.basic_auth 'REPLACE_API_KEY', ''
  response = Net::HTTP.start(url.host, url.port) do |http|
    http.request(request)
  end
  puts response.read_body
end
        


var client = new RestClient("https://app.nanonets.com/api/v2/ImageCategorization/UploadFile/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "Multipart/form-data");
request.AddParameter("modelId", "REPLACE_MODEL_ID");
request.AddParameter("category", "category1");
request.AddFile("file", "REPLACE_IMAGE_PATH.jpg");
IRestResponse response = client.Execute(request);
        


private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpeg");

OkHttpClient client = new OkHttpClient();

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("modelId", "REPLACE_MODEL_ID")
        .addFormDataPart("category", "category1")
        .addFormDataPart("file", "REPLACE_IMAGE_PATH.jpg", RequestBody.create(MEDIA_TYPE_JPG, new File("REPLACE_IMAGE_PATH.jpg")))
        .build();

request = new Request.Builder()
        .url("https://app.nanonets.com/api/v2/ImageCategorization/UploadFile/")
        .post(requestBody)
        .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
        .build();

Response response = client.newCall(request).execute();

        

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "classification",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

You can use this endpoint to upload training images for a category (for the specified model) using locally stored files. You will receive model information along with total number of images per category on successful execution.

HTTP Request

GET http://app.nanonets.com/api/v2/ImageCategorization/UploadFile/

Query Parameters

Parameter Description
modelId Unique id of the model
category Category image belongs to
file file as part of multipart request

Errors

You can see the json structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
404 Model does not exists Check if the model id exists
400 Category not valid for model Check if this model has the category used in request
400 File missing Check if you have included the file in the request
400 Incorrect image Check if file you included is valid PNG or JPEG file

Try it live

You can try the api live here

Train

Train model



import requests

url = 'https://app.nanonets.com/api/v2/ImageCategorization/Train/'

headers = {'authorization': 'Basic REPLACE_API_KEY'}

querystring = {'modelId': 'REPLACE_MODEL_ID'}

response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), params=querystring)

print(response.text)
        

curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ImageCategorization/Train/?modelId=REPLACE_MODEL_ID' \
  -u 'REPLACE_API_KEY'
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ImageCategorization/Train/?modelId=REPLACE_MODEL_ID"

    req, _ := http.NewRequest("POST", url, nil)

    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = null;

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ImageCategorization/Train/?modelId=REPLACE_MODEL_ID");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ImageCategorization/Train/?modelId=REPLACE_MODEL_ID')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request.basic_auth 'REPLACE_API_KEY', ''

response = http.request(request)
puts response.read_body
        


var client = new RestClient("https://app.nanonets.com/api/v2/ImageCategorization/Train/?modelId=REPLACE_MODEL_ID");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
IRestResponse response = client.Execute(request);
        


OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("https://app.nanonets.com/api/v2/ImageCategorization/Train/?modelId=REPLACE_MODEL_ID")
  .post(null)
  .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
  .build();

Response response = client.newCall(request).execute();
        

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "classification",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

You can use this endpoint to train a model after uploading images for each category. You can use the same endpoint to retrain a model after uploading more images to improve the model.

HTTP Request

POST http://app.nanonets.com/api/v2/ImageCategorization/Train/

POST Parameters

Parameter Description
modelId Unique id of the model

Errors

You can see the json structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
404 Model does not exists Check if the model id exists
400 Model not ready for training Check if the images for the model are uploaded

Try it live

You can try the api live here

Prediction

The prediction object

JSON structure for the prediction object :


{
  "model_id": "string",
  "message": "string",
  "result": [
    {
      "prediction": [
        {
          "category": "string",
          "probability": float
        }
      ],
      "input": "string"
    }
  ]
}
        
Attributes Description
model_id Unique id for the model
message Additional information if any
result Array of result object which includes predictions for inputs given
prediction Prediction probability values for each category in model
input Input for which prediction is given. Filename or Url based on input

Prediction for image urls


curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/' \
  --header 'accept: application/x-www-form-urlencoded' \
  -d 'modelId=REPLACE_MODEL_ID&urls=https://goo.gl/ICoiHc' \
  -u 'REPLACE_API_KEY'
        


import requests

url = 'https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/'

headers = {
    'accept': 'application/x-www-form-urlencoded'
}

data = {'modelId': 'REPLACE_MODEL_ID', 'urls' : ['https://goo.gl/ICoiHc']}

response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), data=data)

print(response.text)
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/"

    data := url.Values{}
    data.Set("modelId", "REPLACE_MODEL_ID")
    data.Add("urls", "https://goo.gl/ICoiHc")

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = 'modelId=REPLACE_MODEL_ID&urls=https://goo.gl/ICoiHc';

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);

        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["accept"] = 'application/x-www-form-urlencoded'
request.basic_auth 'REPLACE_API_KEY', ''

request.set_form_data({'modelId' => 'REPLACE_MODEL_ID', 'urls' => ['https://goo.gl/ICoiHc']})

response = http.request(request)
puts response.read_body
        


var client = new RestClient("https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "application/x-www-form-urlencoded");
request.AddParameter("modelId", "REPLACE_MODEL_ID");
request.AddParameter("urls", "https://goo.gl/ICoiHc");
IRestResponse response = client.Execute(request);
        


OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
        .add("modelId", "REPLACE_MODEL_ID")
        .add("urls", "https://goo.gl/ICoiHc").build();

Request request = new Request.Builder()
    .url("https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/")
    .post(formBody)
    .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
    .build();

Response response = client.newCall(request).execute();
        

JSON structure for the prediction object :


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "message": "Prediction successful",
  "result": [
    {
      "prediction": [
        {
          "category": "category1",
          "probability": 0.9
        },
        {
          "category": "category2",
          "probability": 0.1
        }
      ],
      "input": "string"
    }
  ]
}
        

Use the model to predict which one of the categories an image (given the image url) belongs to. You can specify multiple image urls.

HTTP Request

POST http://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/

POST Parameters

Parameter Description
modelId Unique id of the model
urls array of urls for images

Errors

You can see the json structure for the error object in right column. Here are possible error codes and reasons.

Code Reason Message
202 Request partially successful One or more urls might not be correct or got no response
404 Model does not exists Check if the model id exists
400 Urls missing Check if you have an included array of image urls
402 Exhausted Free API Calls You have exhausted your free API calls please change your plan here

Try it live

You can try the api live here

Prediction for image file



import requests

url = 'https://app.nanonets.com/api/v2/ImageCategorization/LabelFile/'

data = {'file': open('REPLACE_IMAGE_PATH.jpg', 'rb'), \
    'modelId': ('', 'REPLACE_MODEL_ID')}

response = requests.post(url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), files=data)

print(response.text)
        

curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ImageCategorization/LabelFile/' \
  --header 'accept: multipart/form-data' \
  -u 'REPLACE_API_KEY' \
  -F 'modelId=REPLACE_MODEL_ID' \
  -F 'file=@REPLACE_IMAGE_PATH.jpg'
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ImageCategorization/LabelFile/"

    file, err := os.Open("REPLACE_IMAGE_PATH.jpg")
    if err != nil {
        return nil, err
    }

    defer file.Close()

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    part, err := writer.CreateFormFile("file", filepath.Base("REPLACE_IMAGE_PATH.jpg"))
    if err != nil {
        return nil, err
    }
    _, err = io.Copy(part, file)

    writer.WriteField("modelId", "REPLACE_MODEL_ID")

    contentType := writer.FormDataContentType()

    err = writer.Close()
    if err != nil {
        return nil, err
    }

    req, _ := http.NewRequest("POST", url, body)

    req.Header.Add("Content-Type", contentType)
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = new FormData();
data.append('modelId', 'REPLACE_MODEL_ID');
data.append('file', 'REPLACE_IMAGE_PATH.jpg');

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ImageCategorization/LabelFile/");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        

require 'uri'
require 'net/http'
require 'net/http/post/multipart'

http = Net::HTTP.new(url.host, url.port)

File.open('REPLACE_IMAGE_PATH.jpg') do |jpg|
  request = Net::HTTP::Post::Multipart.new(url.path,
    'file' => UploadIO.new(jpg, 'image/jpeg', 'REPLACE_IMAGE_PATH.jpg')
    'modelId' => 'REPLACE_MODEL_ID'
  request.basic_auth 'REPLACE_API_KEY', ''
  response = Net::HTTP.start(url.host, url.port) do |http|
    http.request(request)
  end
  puts response.read_body
end
        

var client = new RestClient("https://app.nanonets.com/api/v2/ImageCategorization/LabelFile/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "Multipart/form-data");
request.AddParameter("modelId", "REPLACE_MODEL_ID");
request.AddFile("file", "REPLACE_IMAGE_PATH.jpg");
IRestResponse response = client.Execute(request);
        


OkHttpClient client = new OkHttpClient();
private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpeg");

OkHttpClient client = new OkHttpClient();

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("modelId", "REPLACE_MODEL_ID")
        .addFormDataPart("file", "REPLACE_IMAGE_PATH.jpg", RequestBody.create(MEDIA_TYPE_JPG, new File("REPLACE_IMAGE_PATH.jpg")))
        .build();

request = new Request.Builder()
        .url("https://app.nanonets.com/api/v2/ImageCategorization/UploadFile/")
        .post(requestBody)
        .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
        .build();

Response response = client.newCall(request).execute();

        

JSON structure for the prediction object :


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "message": "Prediction successful",
  "result": [
    {
      "prediction": [
        {
          "category": "category1",
          "probability": 0.9
        },
        {
          "category": "category2",
          "probability": 0.1
        }
      ],
      "input": "string"
    }
  ]
}
        

Use the model to predict which one of the categories an image (given an image file) belongs to.

HTTP Request

POST http://app.nanonets.com/api/v2/ImageCategorization/LabelFile/

POST Parameters

Parameter Description
modelId Unique id of the model
file file as part of multipart request

Errors

You can see the json structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
404 Model does not exists Check if the model id exists
400 File missing Check if you have included a file in the request
400 Incorrect image Check if file you included is a valid PNG or JPEG
402 Exhausted Free API Calls You have exhausted your free API calls please change your plan here

Try it live

You can try the api live here

Object Detection

Models

The model object

JSON structure for model object:


[
  {
    "model_id": "string",
    "model_type": "string",
    "state": int
    "categories": [
      {
        "name": "string",
        "count": int
      }
    ]
  }
]
        
Attributes Description
model_id Unique id for the model
model_type Type of model. Possible values are:
  • classification: Image classification model
  • localization: Object detection model
  • textclassification: Text classification model
state Current state of model. Possible values are:
  • -1: Error in model training
  • 0: Model created. No training data uploaded yet
  • 1: Training data uploaded. Need to annotate data
  • 2: Training data annotated. Need to start training
  • 3: Model in training queue
  • 4: Model currently training
  • 5: Model hosted. Can be used for prediction

Get All models for a user


import requests

url = 'https://app.nanonets.com/api/v2/ObjectDetection/Models/'

response = requests.request('GET', url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''))

print(response.text)
        

curl --request GET \
  --url https://app.nanonets.com/api/v2/ObjectDetection/Models/ \
  -u 'REPLACE_API_KEY'

        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ObjectDetection/Models/"

    req, _ := http.NewRequest("GET", url, nil)

    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = null;

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://app.nanonets.com/api/v2/ObjectDetection/Models/");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ObjectDetection/Models/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)
request.basic_auth 'REPLACE_API_KEY', ''

response = http.request(request)
puts response.read_body

        


var client = new RestClient("https://app.nanonets.com/api/v2/ObjectDetection/Models/");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("REPLACE_API_KEY:")));
IRestResponse response = client.Execute(request);

        

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("https://app.nanonets.com/api/v2/ObjectDetection/Models/")
  .get()
  .addHeader("authorization", Credentials.basic("REPLACE_API_KEY", ""))
  .build();

Response response = client.newCall(request).execute();
        

This endpoint returns information of all models created by user.

HTTP Request

GET http://app.nanonets.com/api/v2/ObjectDetection/Models/

Query Parameters

Parameter Default Description
No parameters

The code above returns the model object in the format below:


[
  {
    "model_id": "00000000-0000-0000-0000-000000000000",
    "model_type": "localization",
    "state": 0
    "categories": [
      {
        "name": "category1",
        "count": 0
      },
      {
        "name": "category2",
        "count": 0
      }
    ]
  }
]
        

Response

The code above returns a JSON array of the model object as shown in right side pane populated with default values

Try it live

You can try the api live here

Get a specific model information



import requests

url = 'https://app.nanonets.com/api/v2/ObjectDetection/Model/'

querystring = {'modelId': 'REPLACE_MODEL_ID'}

response = requests.request('GET', url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY',''), params=querystring)

print(response.text)

        

curl --request GET \
  --url 'https://app.nanonets.com/api/v2/ObjectDetection/Model/?id=REPLACE_MODEL_ID' \
  -u 'REPLACE_API_KEY'
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ObjectDetection/Model/?id=REPLACE_MODEL_ID"

    req, _ := http.NewRequest("GET", url, nil)

    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = null;

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://app.nanonets.com/api/v2/ObjectDetection/Model/?id=REPLACE_MODEL_ID");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);

        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ObjectDetection/Model/?id=REPLACE_MODEL_ID')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)

request.basic_auth 'REPLACE_API_KEY', ''

response = http.request(request)
puts response.read_body

        


var client = new RestClient("https://app.nanonets.com/api/v2/ObjectDetection/Model/?id=REPLACE_MODEL_ID");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("REPLACE_API_KEY:")));
IRestResponse response = client.Execute(request);

        


OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("https://app.nanonets.com/api/v2/ObjectDetection/Model/?id=REPLACE_MODEL_ID")
  .get()
  .addHeader("authorization", Credentials.basic("REPLACE_API_KEY", ""))
  .build();

Response response = client.newCall(request).execute();

        

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "localization",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

Response 404: Model does not exists


{
  "message": "Does not exists",
  "code": 404,
  "errors": [
    {
      "reason": "Model does not exists",
      "message": "Check if model id is correct in request"
    }
  ]
}
        

This endpoint retrieves a specific model's details given it's id.

HTTP Request

GET http://app.nanonets.com/api/v2/ObjectDetection/Model/

URL Parameters

Parameter Description
id The ID of the model to retrieve

Errors

You can see the JSON structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
404 Model does not exists Check if you have entered correct model id with valid API key

Try it live

You can try the api live here

Create new model



import requests

url = 'https://app.nanonets.com/api/v2/ObjectDetection/Model/'

headers = {
    'accept': 'application/x-www-form-urlencoded'
}

data = {'categories' : ['category1', 'category2']}

response = requests.request("POST", url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), data=data)

print(response.text)

        


curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ObjectDetection/Model/' \
  --header 'accept: application/x-www-form-urlencoded' \
  -u 'REPLACE_API_KEY' \
  -d 'categories=category1&categories=category2'

          


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
    "bytes"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ObjectDetection/Model/"

    data := url.Values{}
    data.Set("categories", "category1")
    data.Add("categories", "category2")

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = "categories=category1&categories=category2";

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ObjectDetection/Model/");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ObjectDetection/Model/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["accept"] = 'application/x-www-form-urlencoded'
request.basic_auth 'REPLACE_API_KEY', ''

request.set_form_data({'categories' => ['category1', 'category2']})

response = http.request(request)
puts response.read_body
        


var client = new RestClient("https://app.nanonets.com/api/v2/ObjectDetection/Model/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "application/x-www-form-urlencoded");
request.AddParameter("categories", "category1");
request.AddParameter("categories", "category2");
IRestResponse response = client.Execute(request);

        


OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
    .add("categories", "category1")
    .add("categories", "category2").build();

Request request = new Request.Builder()
    .url("https://app.nanonets.com/api/v2/ObjectDetection/Model/")
    .post(formBody)
    .addHeader("authorization", Credentials.basic("REPLACE_API_KEY", ""))
    .build();

Response response = client.newCall(request).execute();
          

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "localization",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

Response 400: Bad request


{
  "message": "Does not exists",
  "code": 404,
  "errors": [
    {
      "reason": "Model does not exists",
      "message": "Check if model id is correct in request"
    }
  ]
}
        

You can create a new model using this endpoint. A successful API call will return the json strcutre of the newly created model. You can then use the model's id to upload images for each category and then retrain the model.

HTTP Request

POST http://app.nanonets.com/api/v2/ObjectDetection/Model/

POST Parameters

Parameter Description
categories Categories for model

Errors

You can see the json structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
400 Zero or One category in request Add two or more categories in parameters

Try it live

You can try the api live here

Upload

Upload training images by url



import requests

url = 'https://app.nanonets.com/api/v2/ObjectDetection/UploadUrls/'

headers = {
    'accept': 'application/x-www-form-urlencoded'
}

data = {'modelId' : 'REPLACE_MODEL_ID', 'data': '[{"filename":"https://goo.gl/ICoiHc", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]', 'urls': ['https://goo.gl/ICoiHc']}

response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), data=data)

print(response.text)
        

curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ObjectDetection/UploadUrls/' \
  --header 'accept: application/x-www-form-urlencoded' \
  -d 'modelId=REPLACE_MODEL_ID&data=[{"filename":"https://goo.gl/ICoiHc", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]&urls=https://goo.gl/ICoiHc' \
  -u 'REPLACE_API_KEY'
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ObjectDetection/UploadUrls/"

    data := url.Values{}
    data.Set("modelId", "REPLACE_MODEL_ID")
    data.Add("data", `[{"filename":"https://goo.gl/ICoiHc", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]`)
    data.Add("urls", "https://goo.gl/ICoiHc")

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = 'modelId=REPLACE_MODEL_ID&data=[{"filename":"https://goo.gl/ICoiHc", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]&urls=https://goo.gl/ICoiHc';

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ObjectDetection/UploadUrls/");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ObjectDetection/UploadUrls/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["accept"] = 'application/x-www-form-urlencoded'
request.basic_auth 'REPLACE_API_KEY', ''

request.set_form_data({'modelId' => 'REPLACE_MODEL_ID', 'data' => '[{"filename":"https://goo.gl/ICoiHc", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]', 'urls' => ['https://goo.gl/ICoiHc']})

response = http.request(request)
puts response.read_body

        


var client = new RestClient("https://app.nanonets.com/api/v2/ObjectDetection/UploadUrls/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "application/x-www-form-urlencoded");
request.AddParameter("modelId", "REPLACE_MODEL_ID");
request.AddParameter("data", "[{\"filename":\"https://goo.gl/ICoiHc\", \"object\": [{\"name\":\"category\", \"bndbox\": {\"xmin\": 1,\"ymin\": 1,\"xmax\": 100, \"ymax\": 100}}]}]");
request.AddParameter("urls", "https://goo.gl/ICoiHc");
IRestResponse response = client.Execute(request);
        


OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
        .add("modelId", "REPLACE_MODEL_ID")
        .add("data", "[{\"filename":\"https://goo.gl/ICoiHc\", \"object\": [{\"name\":\"category\", \"bndbox\": {\"xmin\": 1,\"ymin\": 1,\"xmax\": 100, \"ymax\": 100}}]}]")
        .add("urls", "https://goo.gl/ICoiHc").build();

Request request = new Request.Builder()
        .url("https://app.nanonets.com/api/v2/ObjectDetection/UploadUrls/")
        .post(formBody)
        .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
        .build();

Response response = client.newCall(request).execute();
        

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "localization",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

You can use this endpoint to upload training images for a category (for the specified model) by image urls. You can upload multiple images in the same request by adding an array of urls. You will receive model information along with total number of images per category on successful execution.

HTTP Request

POST http://app.nanonets.com/api/v2/ObjectDetection/UploadUrls/

POST Parameters

Parameter Description
modelId Unique id of the model
data Annotation details in JSON format
urls array of urls for images

Errors

You can see the json structure for the error object in right column. Here are possible error codes and reasons.

Code Reason Message
202 Request partially successful One or more urls might not be correct or got no response
404 Model does not exists Check if the model id exists
400 Category not valid for model Check if this model has the category used in the request
400 Urls missing Check if you have included an array of image urls

Try it live

You can try the api live here

Upload training images by file



import requests

url = 'https://app.nanonets.com/api/v2/ObjectDetection/UploadFile/'

data = {'file' :open('REPLACE_IMAGE_PATH.jpg', 'rb'), \
    'data' :('', '[{"filename":"REPLACE_IMAGE_PATH.jpg", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]'), \
    'modelId' :('', 'REPLACE_MODEL_ID')}

response = requests.post(url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), files=data)

print(response.text)
        

curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ObjectDetection/UploadFile/' \
  --header 'accept: multipart/form-data' \
  -u 'REPLACE_API_KEY' \
  -F 'data=[{"filename":"REPLACE_IMAGE_PATH.jpg", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]' \
  -F 'modelId=REPLACE_MODEL_ID' \
  -F 'file=@REPLACE_IMAGE_PATH.jpg'
        

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ObjectDetection/UploadFile/"

    file, err := os.Open('REPLACE_IMAGE_PATH.jpg')
    if err != nil {
        return nil, err
    }

    defer file.Close()

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    part, err := writer.CreateFormFile("file", filepath.Base("REPLACE_IMAGE_PATH.jpg"))
    if err != nil {
        return nil, err
    }
    _, err = io.Copy(part, file)

    writer.WriteField("data", `[{"filename":"REPLACE_IMAGE_PATH.jpg", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]`)
    writer.WriteField("modelId", "REPLACE_MODEL_ID")

    contentType := writer.FormDataContentType()

    err = writer.Close()
    if err != nil {
        return nil, err
    }

    req, _ := http.NewRequest("POST", url, body)

    req.Header.Add("Content-Type", contentType)
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = new FormData();
data.append('data', '[{"filename":"REPLACE_IMAGE_PATH.jpg", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]');
data.append('modelId', 'REPLACE_MODEL_ID');
data.append('file', 'REPLACE_IMAGE_PATH.jpg');

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ObjectDetection/UploadFile/");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'
require 'net/http/post/multipart'


url = URI('https://app.nanonets.com/api/v2/ObjectDetection/UploadFile/')

http = Net::HTTP.new(url.host, url.port)

File.open('REPLACE_IMAGE_PATH.jpg') do |jpg|
  request = Net::HTTP::Post::Multipart.new(url.path,
    'file' => UploadIO.new(jpg, 'image/jpeg', 'REPLACE_IMAGE_PATH.jpg')
    'modelId' => 'REPLACE_MODEL_ID',
    'data' => '[{"filename":"REPLACE_IMAGE_PATH.jpg", "object": [{"name":"category", "bndbox": {"xmin": 1,"ymin": 1,"xmax": 100, "ymax": 100}}]}]')
  request.basic_auth 'REPLACE_API_KEY', ''
  response = Net::HTTP.start(url.host, url.port) do |http|
    http.request(request)
  end
  puts response.read_body
end
        


var client = new RestClient("https://app.nanonets.com/api/v2/ObjectDetection/UploadFile/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "Multipart/form-data");
request.AddParameter("modelId", "REPLACE_MODEL_ID");
request.AddParameter("data", "[{\"filename\":\"REPLACE_IMAGE_PATH.jpg\", \"object\": [{\"name\":\"category\", \"bndbox\": {\"xmin\": 1,\"ymin\": 1,\"xmax\": 100, \"ymax\": 100}}]}]");
request.AddFile("file", "REPLACE_IMAGE_PATH.jpg");
IRestResponse response = client.Execute(request);
        


private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpeg");

OkHttpClient client = new OkHttpClient();

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("modelId", "REPLACE_MODEL_ID")
        .addFormDataPart("data", "[{\"filename\":\"REPLACE_IMAGE_PATH.jpg\", \"object\": [{\"name\":\"category\", \"bndbox\": {\"xmin\": 1,\"ymin\": 1,\"xmax\": 100, \"ymax\": 100}}]}]")
        .addFormDataPart("file", "REPLACE_IMAGE_PATH.jpg", RequestBody.create(MEDIA_TYPE_JPG, new File("REPLACE_IMAGE_PATH.jpg")))
        .build();

request = new Request.Builder()
        .url("https://app.nanonets.com/api/v2/ObjectDetection/UploadFile/")
        .post(requestBody)
        .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
        .build();

Response response = client.newCall(request).execute();

        

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "localization",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

You can use this endpoint to upload training images for a category (for the specified model) using locally stored files. You will receive model information along with total number of images per category on successful execution.

HTTP Request

GET http://app.nanonets.com/api/v2/ObjectDetection/UploadFile/

Query Parameters

Parameter Description
modelId Unique id of the model
data Annotation data in JSON format
file file as part of multipart request

Errors

You can see the json structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
404 Model does not exists Check if the model id exists
400 Category not valid for model Check if this model has the category used in request
400 File missing Check if you have included the file in the request
400 Incorrect image Check if file you included is valid PNG or JPEG file

Try it live

You can try the api live here

Train

Train model



import requests

url = 'https://app.nanonets.com/api/v2/ObjectDetection/Train/'

headers = {'authorization': 'Basic REPLACE_API_KEY'}

querystring = {'modelId': 'REPLACE_MODEL_ID'}

response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), params=querystring)

print(response.text)
        

curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ObjectDetection/Train/?modelId=REPLACE_MODEL_ID' \
  -u 'REPLACE_API_KEY'
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ObjectDetection/Train/?modelId=REPLACE_MODEL_ID"

    req, _ := http.NewRequest("POST", url, nil)

    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = null;

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ObjectDetection/Train/?modelId=REPLACE_MODEL_ID");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ObjectDetection/Train/?modelId=REPLACE_MODEL_ID')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request.basic_auth 'REPLACE_API_KEY', ''

response = http.request(request)
puts response.read_body
        


var client = new RestClient("https://app.nanonets.com/api/v2/ObjectDetection/Train/?modelId=REPLACE_MODEL_ID");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
IRestResponse response = client.Execute(request);
        


OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("https://app.nanonets.com/api/v2/ObjectDetection/Train/?modelId=REPLACE_MODEL_ID")
  .post(null)
  .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
  .build();

Response response = client.newCall(request).execute();
        

The code above returns the model object in the format below:


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "model_type": "localization",
  "state": 0,
  "categories": [
    {
      "name": "category1",
      "count": 0
    },
    {
      "name": "category2",
      "count": 0
    }
  ]
}
        

You can use this endpoint to train a model after uploading images for each category. You can use the same endpoint to retrain a model after uploading more images to improve the model.

HTTP Request

POST http://app.nanonets.com/api/v2/ObjectDetection/Train/

POST Parameters

Parameter Description
modelId Unique id of the model

Errors

You can see the json structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
404 Model does not exists Check if the model id exists
400 Model not ready for training Check if the images for the model are uploaded

Try it live

You can try the api live here

Prediction

The prediction object

JSON structure for the prediction object :


{
  "model_id": "string",
  "message": "string",
  "result": [
    {
      "input": "string",
      "prediction": [
        {
          "label": "string",
          "xmin": int,
          "xmax": int,
          "ymin": int,
          "ymax": int,
        }
      ]
    }
  ]
}
        
Attributes Description
model_id Unique id for the model
message Additional information if any
result Array of result object which includes predictions for inputs given
prediction Array of bounding box predictions
input Input for which prediction is given. Filename or Url based on input
label Object detected in input image
xmin X-Coordinate of Top left pixel of bounding box
ymin Y-Coordinate of Top left pixel of bounding box
xmax X-Coordinate of Bottom right pixel of bounding box
ymax Y-Coordinate of Bottom right pixel of bounding box

Prediction for image urls


curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ObjectDetection/LabelUrls/' \
  --header 'accept: application/x-www-form-urlencoded' \
  -d 'modelId=REPLACE_MODEL_ID&urls=https://goo.gl/ICoiHc' \
  -u 'REPLACE_API_KEY'
        


import requests

url = 'https://app.nanonets.com/api/v2/ObjectDetection/LabelUrls/'

headers = {
    'accept': 'application/x-www-form-urlencoded'
}

data = {'modelId': 'REPLACE_MODEL_ID', 'urls' : ['https://goo.gl/ICoiHc']}

response = requests.request('POST', url, headers=headers, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), data=data)

print(response.text)
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ObjectDetection/LabelUrls/"

    data := url.Values{}
    data.Set("modelId", "REPLACE_MODEL_ID")
    data.Add("urls", "https://goo.gl/ICoiHc")

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = 'modelId=REPLACE_MODEL_ID&urls=https://goo.gl/ICoiHc';

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ObjectDetection/LabelUrls/");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);

        


require 'uri'
require 'net/http'

url = URI('https://app.nanonets.com/api/v2/ObjectDetection/LabelUrls/')

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["accept"] = 'application/x-www-form-urlencoded'
request.basic_auth 'REPLACE_API_KEY', ''

request.set_form_data({'modelId' => 'REPLACE_MODEL_ID', 'urls' => ['https://goo.gl/ICoiHc']})

response = http.request(request)
puts response.read_body
        


var client = new RestClient("https://app.nanonets.com/api/v2/ObjectDetection/LabelUrls/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "application/x-www-form-urlencoded");
request.AddParameter("modelId", "REPLACE_MODEL_ID");
request.AddParameter("urls", "https://goo.gl/ICoiHc");
IRestResponse response = client.Execute(request);
        


OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
        .add("modelId", "REPLACE_MODEL_ID")
        .add("urls", "https://goo.gl/ICoiHc").build();

Request request = new Request.Builder()
    .url("https://app.nanonets.com/api/v2/ObjectDetection/LabelUrls/")
    .post(formBody)
    .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
    .build();

Response response = client.newCall(request).execute();
        

JSON structure for the prediction object :


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "message": "Prediction successful",
  "result": [
    {
      "input": "string",
      "prediction": [
        {
          "label": "category1",
          "xmin": 0,
          "ymin": 0,
          "xmax": 100,
          "ymax": 100,
        }
      ]
    }
  ]
}
        

Use the model to predict which one of the categories an image (given the image url) belongs to. You can specify multiple image urls.

HTTP Request

POST http://app.nanonets.com/api/v2/ObjectDetection/LabelUrls/

POST Parameters

Parameter Description
modelId Unique id of the model
urls array of urls for images

Errors

You can see the json structure for the error object in right column. Here are possible error codes and reasons.

Code Reason Message
202 Request partially successful One or more urls might not be correct or got no response
404 Model does not exists Check if the model id exists
400 Urls missing Check if you have an included array of image urls
402 Exhausted Free API Calls You have exhausted your free API calls please change your plan here

Try it live

You can try the api live here

Prediction for image file



import requests

url = 'https://app.nanonets.com/api/v2/ObjectDetection/LabelFile/'

data = {'file': open('REPLACE_IMAGE_PATH.jpg', 'rb'), \
    'modelId': ('', 'REPLACE_MODEL_ID')}

response = requests.post(url, auth=requests.auth.HTTPBasicAuth('REPLACE_API_KEY', ''), files=data)

print(response.text)
        

curl --request POST \
  --url 'https://app.nanonets.com/api/v2/ObjectDetection/LabelFile/' \
  --header 'accept: multipart/form-data' \
  -u 'REPLACE_API_KEY' \
  -F 'modelId=REPLACE_MODEL_ID' \
  -F 'file=@REPLACE_IMAGE_PATH.jpg'
        


package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://app.nanonets.com/api/v2/ObjectDetection/LabelFile/"

    file, err := os.Open("REPLACE_IMAGE_PATH.jpg")
    if err != nil {
        return nil, err
    }

    defer file.Close()

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    part, err := writer.CreateFormFile("file", filepath.Base("REPLACE_IMAGE_PATH.jpg"))
    if err != nil {
        return nil, err
    }
    _, err = io.Copy(part, file)

    writer.WriteField("modelId", "REPLACE_MODEL_ID")

    contentType := writer.FormDataContentType()

    err = writer.Close()
    if err != nil {
        return nil, err
    }

    req, _ := http.NewRequest("POST", url, body)

    req.Header.Add("Content-Type", contentType)
    req.SetBasicAuth("REPLACE_API_KEY", "")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}
        


var data = new FormData();
data.append('modelId', 'REPLACE_MODEL_ID');
data.append('file', 'REPLACE_IMAGE_PATH.jpg');

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://app.nanonets.com/api/v2/ObjectDetection/LabelFile/");
xhr.setRequestHeader("authorization", "Basic " + btoa("REPLACE_API_KEY:"));

xhr.send(data);
        

require 'uri'
require 'net/http'
require 'net/http/post/multipart'

http = Net::HTTP.new(url.host, url.port)

File.open('REPLACE_IMAGE_PATH.jpg') do |jpg|
  request = Net::HTTP::Post::Multipart.new(url.path,
    'file' => UploadIO.new(jpg, 'image/jpeg', 'REPLACE_IMAGE_PATH.jpg')
    'modelId' => 'REPLACE_MODEL_ID'
  request.basic_auth 'REPLACE_API_KEY', ''
  response = Net::HTTP.start(url.host, url.port) do |http|
    http.request(request)
  end
  puts response.read_body
end
        

var client = new RestClient("https://app.nanonets.com/api/v2/ObjectDetection/LabelFile/");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic REPLACE_API_KEY");
request.AddHeader("accept", "Multipart/form-data");
request.AddParameter("modelId", "REPLACE_MODEL_ID");
request.AddFile("file", "REPLACE_IMAGE_PATH.jpg");
IRestResponse response = client.Execute(request);
        


OkHttpClient client = new OkHttpClient();
private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpeg");

OkHttpClient client = new OkHttpClient();

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("modelId", "REPLACE_MODEL_ID")
        .addFormDataPart("file", "REPLACE_IMAGE_PATH.jpg", RequestBody.create(MEDIA_TYPE_JPG, new File("REPLACE_IMAGE_PATH.jpg")))
        .build();

request = new Request.Builder()
        .url("https://app.nanonets.com/api/v2/ObjectDetection/UploadFile/")
        .post(requestBody)
        .addHeader("Authorization", Credentials.basic("REPLACE_API_KEY", ""))
        .build();

Response response = client.newCall(request).execute();

        

JSON structure for the prediction object :


{
  "model_id": "00000000-0000-0000-0000-000000000000",
  "message": "Prediction successful",
  "result": [
    {
      "input": "string",
      "prediction": [
        {
          "label": "category1",
          "xmin": 0,
          "ymin": 0,
          "xmax": 100,
          "ymax": 100,
        }
      ]
    }
  ]
}
        

Use the model to predict which one of the categories an image (given an image file) belongs to.

HTTP Request

POST http://app.nanonets.com/api/v2/ObjectDetection/LabelFile/

POST Parameters

Parameter Description
modelId Unique id of the model
file file as part of multipart request

Errors

You can see the json structure for the error object in the right hand column.

Below are possible error codes and corresponding reasons:

Code Reason Message
404 Model does not exists Check if the model id exists
400 File missing Check if you have included a file in the request
400 Incorrect image Check if file you included is a valid PNG or JPEG
402 Exhausted Free API Calls You have exhausted your free API calls please change your plan here

Try it live

You can try the api live here