First Indico Workshop HTTP API Adrian Mönnich 29-27 May 2013 CERN.

Slides:



Advertisements
Similar presentations
LiNC Developer Meetup Welcome!. Our job is to make your life easier APIs Tools and workflow Documentation Stay in touch: developers.lithium.com Join the.
Advertisements

COS 461 Fall 1997 Network Objects u first good implementation: DEC SRC Network Objects for Modula-3 u recent implementation: Java RMI (Remote Method Invocation)
Presenter: James Huang Date: Sept. 29,  HTTP and WWW  Bottle Web Framework  Request Routing  Sending Static Files  Handling HTML  HTTP Errors.
© 2008 Cisco Systems, Inc. All rights reserved.Cisco ConfidentialPresentation_ID 1 Chapter 8: Monitoring the Network Connecting Networks.
Bruce Beckles University of Cambridge Computing Service
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
1.  Understanding about How to Working with Server Side Scripting using PHP Framework (CodeIgniter) 2.
XML Configuration Access Protocol (XCAP) Jonathan Rosenberg dynamicsoft.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CSCI 4550/8556 Computer Networks Comer, Chapter 3: Network Programming and Applications.
Getting a Web Page (And what to do once you’ve got it)
C++ fundamentals.
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Using Microsoft Outlook: Basics. Objectives Guided Tour of Outlook –Identification –Views Basics –Contacts –Folders –Web Access Q&A.
First Indico Workshop Basic Administration Guide Alejandro Avilés May 2013 CERN.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Web server and web browser It’s a take and give policy in between client and server through HTTP(Hyper Text Transport Protocol) Server takes a request.
1 Google Checkout API Jingsong Wang Arpril 2, 2007.
Dataface API Essentials Steve Hannah Web Lite Solutions Corp.
Excel 2007 Part (2) Dr. Susan Al Naqshbandi
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1.
JavaScript & jQuery the missing manual Chapter 11
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
JavaScript, Fourth Edition Chapter 12 Updating Web Pages with AJAX.
LiveCycle Data Services Introduction Part 2. Part 2? This is the second in our series on LiveCycle Data Services. If you missed our first presentation,
CSCI 6962: Server-side Design and Programming Web Services.
HTML5 Communication. The Setup Somewhere on the web, a server makes a ”service” available, that we wish to use in a web application The service may offer.
Web Server Administration Web Services XML SOAP. Overview What are web services and what do they do? What is XML? What is SOAP? How are they all connected?
.Net and Web Services Security CS795. Web Services A web application Does not have a user interface (as a traditional web application); instead, it exposes.
Website Development with PHP and MySQL Saving Data.
New Perspectives on XML, 2nd Edition
Serialization. Serialization is the process of converting an object into an intermediate format that can be stored (e.g. in a file or transmitted across.
First Indico Workshop WEB FRAMEWORKS Adrian Mönnich May 2013 CERN.
First Indico Workshop An Introduction to the Indico Software Thomas Baron May 2013 CERN.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Getting Started with OPC.NET OPC.NET Software Client Interface Client Base Server Base OPC Wrapper OPC COM Server Server Interface WCF Alternate.
Copyright © 2012 UNICOM Systems, Inc. Confidential Information z/Ware Product Overview illustro Systems International A Division of UNICOM Global.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Facebook API Kelly Orser. Client Libraries Client libraries will simplify the calls to the platform by reducing the amount of code you have to write.
1 Web Servers (Chapter 21 – Pages( ) Outline 21.1 Introduction 21.2 HTTP Request Types 21.3 System Architecture.
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
Your friend, Bluestem. What is Bluestem? “Bluestem is a software system which enables one or more high-security SSL HTTP servers in a domain (entrusted.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
ICM – API Server & Forms Gary Ratcliffe.
©SoftMooreSlide 1 Introduction to HTML: Forms ©SoftMooreSlide 2 Forms Forms provide a simple mechanism for collecting user data and submitting it to.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
©2003 Paula Matuszek GOOGLE API l Search requests: submit a query string and a set of parameters to the Google Web APIs service and receive in return a.
: Information Retrieval อาจารย์ ธีภากรณ์ นฤมาณนลิณี
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
OE-NIK HP Advanced Programming Web services Standards and protocols Using web services Using web services with asynchronous calls.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Pyragen A PYTHON WRAPPER GENERATOR TO APPLICATION CORE LIBRARIES Fernando PEREIRA, Christian THEIS - HSE/RP EDMS tech note:
Data Virtualization Tutorial… CORS and CIS
Computer Science 111 Fundamentals of Programming I
Topics Introduction to File Input and Output
Computer Science 111 Fundamentals of Programming I
COMPUTER PROGRAMMING SKILLS
Topics Introduction to File Input and Output
Presentation transcript:

First Indico Workshop HTTP API Adrian Mönnich May 2013 CERN

API Uhh… what’s an API and why do we need one? An application programming interface (API) is a protocol intended to be used as an interface by software components to communicate with each other. Wikipedia

Before the api export.py Not powerful at all: Only events inside categories XML, RSS, iCal or HTML  Accessing it requires an XML parser Protection? Not really  Must be restricted to trusted machines by IP Reusable code? None / export.py?fid=2l12&date=today&days=1000&of=xml

And the developers said… …let there be a proper API… …and they created one

Design ideas How to make the API awesome? Handle authentication in a clean and secure way (API Keys, OAuth2) Various security levels available (API keys, HMAC signatures, …) Let developers write code for the actual task Serialize Python data structures as JSON, XML, … Provide utilities for common things (relative dates, pagination)

Using the API Before we go into details, look at how it works Indico Administrators: API Modes: Control how strict the API key requirements are At CERN: We always require an API key, but a signature is only needed to access non-public information Persistency: Lowers security a little bit (one leaked URL is valid forever) Allows people to use e.g. a RSS reader (cannot sign requests)

Using the API Before we go into details, look at how it works Indico Users: Creating an API key is easy – just one click! Keys can be reset at any time, e.g. in case of a (suspected) leak Last request including IP address and full path is displayed Persistence can be toggled (if enabled globally)

Using the API Before we go into details, look at how it works The same data – available as XML, JSON and sometimes additional more formats (iCal, RSS, HTML) / export/categ/4751.[json|xml|html]

Using the API Before we go into details, look at how it works What it we need a signed request? /export/categ/123.json?limit=10 1. Add the API key to the params … &ak=api-key 2. Add the current timestamp to the params … &timestamp= Sort the query string params alphabetically… ?ak=api- key&limit=10&timestamp=123… 4. Merge path and the sorted query string /export/categ/123.json?ak=api-key&limit=10&timestamp= Create a HMAC-SHA1 signature of this string using the secret key as the key. 6. Append the hex-encoded signature to the query string: …&signature=xxx

EXTENDING THE API Creating a custom API endpoint Let’s keep it simple: We want an API that returns a range of numbers or characters. This does not access any indico-specific data but demonstrates some of the utilities available when using the API as a developer. / export/num/1-10.json / export/char/a-z.json

EXTENDING THE API

Relevant classes HTTPAPIHook : Hooks into the /export/ URL subtree, handles arguments IteratedDataFetcher : Provides pagination, sorting, relative dates, etc. IFossil : Describes how an object is converted to primitives (dict, list, int, str, bool) that can be serialized (JSON, XML, …) later

EXTENDING THE API

The hook, Pt. 1: class RangeHook(HTTPAPIHook): TYPES = ('num', 'char') RE = r'(?P [0-9]+|[a-z])-(?P [0-9]+|[a-z])' DEFAULT_DETAIL = 'simple' MAX_RECORDS = { 'simple': 10, 'palindrome': 5 }

EXTENDING THE API The hook, Pt. 2: Arguments Perform additional validation if necessary Use self._pathParams for arguments from the path regex Use self._queryParams to access arguments in the query string def _getParams(self): super(RangeHook, self)._getParams() self._start = self._pathParams['start'] self._end = self._pathParams['end']

EXTENDING THE API The hook, Pt. 3: The export methods Perform actions/validations specific to the export type Must return an iterator, usually provided by an IteratedDataFetcher def export_num(self, aw): try: start = int(self._start) end = int(self._end) except ValueError: raise HTTPAPIError('Invalid value', 400) return RangeFetcher(aw, self).numbers(start, end) def export_char(self, aw): if len(self._start) != 1 or len(self._end) != 1: raise HTTPAPIError('Invalid character', 400) return RangeFetcher(aw, self).chars(self._start, self._end)

EXTENDING THE API

The fetcher, Pt. 1: Metadata Remember DEFAULT_DETAIL and MAX_RECORDS ? Here we specify how objects are fossilized in those detail levels. More about fossilization later, let’s get some data first! class RangeFetcher(IteratedDataFetcher): DETAIL_INTERFACES = { 'simple': IDummyFossil, 'palindrome': IDummyPalindromeFossil }

EXTENDING THE API The fetcher, Pt. 2: Python iterator magic Remember: We call these methods from our export methods. In this case we just iterate over numbers/characters in the given range. DummyObject ? You will see soon… def numbers(self, start, end): iterable = xrange(int(start), int(end) + 1) iterable = itertools.imap(str, iterable) iterable = itertools.imap(DummyObject, iterable) return self._process(iterable) def chars(self, start, end): iterable = itertools.imap(chr, xrange(ord(start), ord(end) + 1)) # Besides that first line everything is the same like in numbers()

EXTENDING THE API The Dummy Object Usually we deal with custom objects in Indico. Because of historical reasons it is common to have getter methods (yes, we know it is ugly and unpythonic). The fossilization system is built around this  thin wrapper providing a getter for our primitive string values. class DummyObject(object): def __init__(self, value): self.value = value def getValue(self): return self.value

EXTENDING THE API

Fossils IDummyFossil is really simple: It fossilizes the getValue() return value of the actual object to a field named value. For the palindrome detail level we specify a custom callable to generate the value on the fly. The field name is determined automatically again. class IDummyFossil(IFossil): def getValue(self): pass class IDummyPalindromeFossil(IDummyFossil): def getPalindrome(self): pass getPalindrome.produce = lambda x: x.value + x.value[::-1]

EXTENDING THE API Does it work? / export/num/ json?detail=palindrome / export/num/ json / export/num/1-1.xml

EXTENDING THE API Yes! Did you notice the pagination? / export/num/ json?detail=palindrome / export/num/ json / export/num/1-1.xml

What else The API is even more powerful! Caching (unless disabled by the user per-request) POST (to modify things, e.g. booking a room) Additional URL prefixes besides /export/ (e.g. /api/ ) Many things (like the export_* method name) can be changed easily when subclassing HTTPAPIHook Reading the existing code is the best way to get used to it!

EXTENDING THE API

Another example, using class AnnouncementHook(HTTPAPIHook): PREFIX = 'api' TYPES = ('announcement',) RE = r'set' GUEST_ALLOWED = False VALID_FORMATS = ('json', 'xml') COMMIT = True HTTP_POST = True def _getParams(self): super(AnnouncementHook, self)._getParams() self._message = get_query_parameter(self._queryParams, ['message'], '') def api_announcement(self, aw): am = getAnnoucementMgrInstance() am.setText(self._message) return {'message': self._message}

Adrian Mönnich Questions? View the example code on GitHub: [Diff] [Gist]