Monday, 22 August 2016

Making a POST request to SharePoint from an SPFx webpart

Following up on my previous post First SPFx webpart: Get/Set a single value userprofile property in SharePoint, in this post I have separately documented how to make an HTTP POST request from your SPFx webpart. There are lots of posts out already which show you how to make a GET request so I will not cover that here. It is fairly straightforward once you understand all the moving parts.

Some notes around this:

1) The SharePoint Framework (SPFx) is in Developer Preview now so any/all the content of this post is subject to change (although I hope it doesn't)

2) SPFx webparts are not meant for production use at this time.

3) In this sample, I am making a HTTP POST request to SharePoint to create a list.

4) There is a feature/bug in SPFx right now where it adds the odata-version:4 header to every request that does not have the odata header declared. This causes calls to the SharePoint REST API to return malformed responses as it only supports Odata V3 at this time.

So the workaround right now is to explicitly add the odata-version:3 header to every request as shown in the following code.

5) All the code I have shown here is in TypeScript version 1.8.9 as currently dictated by the SharePoint Framework.

Without much further ado, here is the code:

Declare an interface which will be used in the code. This will need to be outside your webpart class.

Now, the code which makes a POST request to create a list:

And my "Developer workbench" list is created:



Hope this helps.

No comments: