Code Monkey home page Code Monkey logo

typeform-python-sdk's Introduction

IMPORTANT NOTE

โš ๏ธ This library hasn't been maintained for a while so we've decided to deprecate it and archive the repository. Feel free to fork it!


typeform

PyPI version Build Status Coverage Status

Python Client wrapper for Typeform API

Table of contents

Installation

pip install typeform

Usage

Initialize

1 - Import client library

  from typeform import Typeform

2 - Create an instance with your personal token

  typeform = Typeform('<api_key>')

3 - Use any of the methods available in the reference

  # will retrieve all forms
  forms: dict = typeform.forms.list()

Reference

Typeform('<api_key>')

  • Creates a new instance of Typeform's Python client
  • Returns an instance with the methods described below
  typeform = Typeform('<api_key>')

Client returns the following properties:

  • forms
  • responses

Each one of them encapsulates the operations related to it (like listing, updating, deleting the resource).

Forms

forms.create(data: dict = {})

Creates a form. Returns dict of created form. See docs.

forms = Typeform('<api_key>').forms
result: dict = forms.create({ 'title': 'Hello World' })

forms.delete(uid: str)

Deletes the form with the given form_id and all of the form's responses. Returns a str based on success of deletion, OK on success, otherwise an error message. See docs.

forms = Typeform('<api_key>').forms
result: str = forms.delete('abc123')

forms.get(uid: str)

Retrieves a form by the given form_id. Includes any theme and images attached to the form as references. See docs.

forms = Typeform('<api_key>').forms
result: dict = forms.get('abc123')

forms.list(page: int = None, pageSize: int = None, search: str = None, workspaceId: str = None)

Retrieves a list of JSON descriptions for all forms in your Typeform account (public and private). Forms are listed in reverse-chronological order based on the last date they were modified. See docs.

forms = Typeform('<api_key>').forms
result: dict = forms.list()

forms.update(uid: str, patch: bool = False, data: dict = {})

Updates an existing form. Defaults to put. put will return the modified form as a dict object. patch will Returns a str based on success of change, OK on success, otherwise an error message. See put docs or patch docs.

forms = Typeform('<api_key>').forms
result: dict = forms.update('abc123', { 'title': 'Hello World, Again' })
result: str = forms.update('abc123', { 'title': 'Hello World, Again' }, patch=True)

forms.messages.get(uid: str)

Retrieves the customizable messages for a form (specified by form_id) using the form's specified language. You can format messages with bold (bold) and italic (italic) text. HTML tags are forbidden. See docs.

forms = Typeform('<api_key>').forms
result: dict = forms.messages.get('abc123')

forms.messages.update(uid: str, data={})

Specifies new values for the customizable messages in a form (specified by form_id). You can format messages with bold (bold) and italic (italic) text. HTML tags are forbidden. Returns a str based on success of change, OK on success, otherwise an error message. See docs.

forms = Typeform('<api_key>').forms
result: str = forms.messages.update('abc123', {
  'label.buttonHint.default': 'New Button Hint'
})

Responses

responses.list(uid: str, pageSize: int = None, since: str = None, until: str = None, after: str = None, before: str = None, includedResponseIds: str = None, completed: bool = None, sort: str = None, query: str = None, fields: List[str] = None)

Returns form responses and date and time of form landing and submission. See docs.

responses = Typeform('<api_key>').responses
result: dict = responses.list('abc123')

responses.delete(uid: str, includedTokens: Union[str, List[str]])

Delete responses to a form. You must specify the included_tokens parameter. Returns a str based on success of deletion, OK on success, otherwise an error message. See docs.

responses = Typeform('<api_key>').responses
result: str = responses.delete('abc123' 'token1')
result: str = responses.delete('abc123' ['token2', 'token3'])

Themes

themes.get(uid: str)

Retrieves a theme by the given theme_id. See docs.

themes = Typeform('<api_key>').themes
result: dict = themes.get('abc123')

themes.list(page: int = None, pageSize: int = None)

Retrieves a list of JSON descriptions for all themes in your Typeform account (public and private). Themes are listed in reverse-chronological order based on the date you added them to your account.

themes = Typeform('<api_key>').themes
result: dict = themes.get('abc123')

Images

images.get(uid: str)

Retrieves an image by the given id. See docs.

images = Typeform('<api_key>').images
result: dict = images.get('abc123')

images.list()

Retrieves a list of JSON descriptions for all images in your Typeform account. Images are listed in reverse-chronological order based on the date you added them to your account.

images = Typeform('<api_key>').images
result: dict = images.list()

images.upload(file_name : str, image : str = None, url : str = None)

Adds an image in your Typeform account.

Specify the URL of your image or send your image in base64 format, which encodes the image data as ASCII text. You can use a tool like Base64 Image Encoder to get the base64 code for the image you want to add.

Tests

Check typeform/test/fixtures.py to configure test run.

typeform-python-sdk's People

Contributors

brettlangdon avatar catalyst-shawn avatar gierlas avatar mathio avatar michaelsolati avatar mrshu avatar mumpo avatar pau-minoves avatar picsoung avatar seti-tf avatar shawncaza avatar tf-security avatar thr44 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typeform-python-sdk's Issues

__init__() got an unexpected keyword argument 'group'

import typeform
form = typeform.Form(api_key='*********', form_id='***')
responses = form.get_responses()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python34\lib\site-packages\typeform\form.py", line 62, in get_responses
    return FormResponses(stats=resp.get('stats'), responses=resp.get('responses'), questions=resp.get('questions'))
  File "C:\Python34\lib\site-packages\typeform\form_response.py", line 81, in __init__
    FormQuestion(**question) for question in questions
  File "C:\Python34\lib\site-packages\typeform\form_response.py", line 81, in <listcomp>
    FormQuestion(**question) for question in questions
TypeError: __init__() got an unexpected keyword argument 'group'

I keep getting this error. I tried installing using pip as well as installing from source.

missing webhooks API?

Any chance we can add the webhooks API into this SDK as well? Seems like it'd follow the same structure as the others.

Adding Images Support

Hi Michael,

Thanks for the package it's great. I'm super new to development and I'm trying to create a tool that generates some forms automatically. Specifically, I need to add images to these forms.
I don't see any support to the images endpoint in your package. Do you plan to build it some time?
Otherwise, I may just give it a shot and send it to you for review when it's done. I've just forked the repo and will start working on it.

Thanks in advance

Addition

Are we interested in a method which pulls responses in the format below.

{
 'question name':'answer'
}

This seems a lot easier for developing with the typeform responses in the backend.

Code refactoring of the whole project

Came across with the project accidentally (actually use TypeForm API in production (but my own implementation)).
After reading the code, I decided that it should be refactored a little, as I noticed many cases that, in my opinion, need to be rewritten:

  • functions in utils seem to me pretty strange and even a little redundant (e.g. mergeDict: since starting with python 3.9 it's enought to use "|" for dicts union), naming of the functions etc.
  • PEP-8 violations: naming of variables (it is preferable to use lower case with underscores), max line length, docstrings, etc
  • There are unused constants in constants.py. And actually it seems like it's better to name it settings.py instead.
  • string formatting. Much more readable (IMHO) use f-strings there (since python 3.6)

actually already have a commit with all these changes: 7910ba4
So I can make a PR

Cannot fetch new responses

Hi,

I have been using this python since a few months without any problem. But since last 2 days its not being able to collect new data.

Responses

Couldn't find how to get the responses, so I've added get_responses function to class Forms

The code reads like this:

 def get_responses(self, uid: str) -> dict:
        """Retrieves the results"""
        return self.__client.request('get', '/forms/%s/responses' % uid)

Problem is, this does not deal with pagination and will not work with more than 25 answers according to the documentation.

Invalid payload error when creating a new Typeform.

Invalid payload error when I try to create a new Typeform.

Expected Behavior

A new form on Typeform should be created.

Current Behavior

No form is created because of an issue I can't fix.

Steps to Reproduce

  1. Copy and paste the code down below in any IDE.
  2. Run the code.
  3. See the error.

Context (Environment)

I've been trying to solve this by myself for hours but I can't find a way to fix this.
This issue is the only problem I have to accomplish my work : I am trying to make a Python application to create a form using the data (questions) in an Excel file.

my_typeform = typeform.Typeform(getpass('Token (text will be hidden): '))

# Create a new form
my_typeform.forms.create({
    'type': 'quiz',
    'title': 'My typeform',
    'fields': [
        {
            'title': 'Nice to meet you, how is your day going?',
            'properties': {
                'randomize': False,
                'allow_multiple_selection': False,
                'allow_other_choice': False,
                'vertical_alignment': True,
                'choices': [
                    {'label': 'Terrific!'},
                    {'label': 'Not so well...'}
                ]
            }
        }
    ]
})

Can't update form using patch

Following the docs, I can't get the following to work:

forms = Typeform('<api_key>').forms

result: str = forms.update('abc123', { 'title': 'Hello World, Again' }, patch=True)

I get a 'The payload is invalid.' error telling me it should be an array in body.

Without setting patch to true I did get a successful update.

More descriptive error messages

Description:

When providing an incorect request body, the error messge is not descriptive enough.

Example:

from typeform import Typeform

r = Typeform("XXXXXXXX").forms.create(data={
    "title": "Incorrect form payload",
    "type": "quiz",
    "theme": https://api.typeform.com/themes/GKFi5U"
})

Raises the following exception:

...
File ~/Projects/coef/typeform-python-sdk/typeform/client.py:41, in Client.__validator(self, result)
     39 if type(body) is dict and body.get('code', None) is not None:
     40     print(body)
---> 41     raise Exception(body.get('description'))
     42 elif result.status_code >= 400:
     43     raise Exception(result.reason)

Exception: The payload is invalid.

If you are to intercept the HTTP response, you will receive a much more verbose error message:

{
    "code": "VALIDATION_ERROR",
    "description": "The payload is invalid.",
    "details": [
        {
            "code": "WRONG_TYPE",
            "description": "should be object,null",
            "field": "/theme",
            "in": "body"
        }
    ]
}

Motivation for or Use Case:

I'd like to handle errors better and understand where the issue is

Related Issues - has a similar issue been reported before?:

#16 Invalid payload error when creating a new Typeform

Environment Configuration:

Latest revision at: ccfe1ec

Suggest a Fix:

# in typeform/client.py L39:
if type(body) is dict and body.get('code', None) is not None:
            print(f"Error code: {body.get('code')}")
            print(f"Error details: {body.get('details')}")
            raise Exception(body.get('description'))

GO SDK + CloudQuery Source Plugin?

Hi Team, hopefully this is right place to ask, if not, I'd appreciate if you can direct me.

I'm the founder of cloudquery.io, a high performance open source ELT framework.

Our users are interested in a Typeform plugin, but as we cannot maintain all the plugins ourselves, I was curious if this would be an interesting collaboration, where we would help implement an initial source plugin, and you will help maintain it.

This will give your users the ability to sync Typeform data to any of their datalakes/data-warehouses/databases easily using any of the growing list of CQ destination plugins.

Best,
Yevgeny

How to receive `user_id` in the callback?

Hi, when I'm constructing the oauth link:

https://api.typeform.com/oauth/authorize?client_id={your_client_id}&redirect_uri=https://results-example.herokuapp.com/callback&scope={scope1}+{scope2}+{scope3}

like this, how can I send user_id above so that I receive the same user_id in the callback request? I have a condition where I want to associate typeform data with the users data I have in my db.

Changing dropdown question content

Hello, I've been able to play around with the data using the query methods but I was wondering how one might go updating question fields using orms_object.update(i.id, {"fields": payload},patch=True), I keep getting payload errors and I'm not sure how to generate correct new ids for each response option.

Excluded Response ID

The documentation mentions an excluded_response_id field but the param doesn't seem to be available. In fact it's not showing here.

My use case is to retrieve only the responses that I have not seen yet (aka new responses) and this flag makes perfect sense.

The response I get back is

TypeError: list() got an unexpected keyword argument 'excludedResponseIds'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.